检测输入占位符是否可见

7
我正在寻找一种方法来检测输入框是否正在显示占位符。
我知道我们可以测试一个特定浏览器是否支持占位符,我会使用这个方法,但这不是我在这里要问的问题。 :placeholder-shown 伪类正好符合我的需求,但它的支持率非常低。比占位符的支持率要低得多。因此,我正在寻找替代方法。
注意:解决方案不能依赖于输入是否已更改或获得值。自动填充的输入既没有技术值,也没有更改。因此,解决方案需要真正检测占位符本身。
4个回答

8
首先,检查元素是否正在使用placeholder属性,然后检查输入值是否为空:

function placeholderActive(selector) {
  var el = document.querySelector(selector);
  if (el.getAttribute('placeholder') && el.value === '') {
    return true;
  }
  return false;
}


var a = placeholderActive('#test1'); // false
var b = placeholderActive('#test2'); // false
var c = placeholderActive('#test3'); // false
var d = placeholderActive('#test4'); // true

console.log(a, b, c, d);
<input id="test1" name="test1" value="123">
<input id="test2" name="test2" placeholder="" value="123">
<input id="test3" name="test3" placeholder="Some Placeholder" value="123">
<input id="test4" name="test4" placeholder="Another placeholder" value="">


4
现在,对于大多数浏览器,我们可以使用:placeholder-shown伪类来检测占位符是否显示。

function placeholderActive(selector) {
  return !!document.querySelector(selector + ':placeholder-shown');
}
const a = placeholderActive('#test1'); // false
const b = placeholderActive('#test2'); // false
const c = placeholderActive('#test3'); // false
const d = placeholderActive('#test4'); // true

console.log(a, b, c, d);
<input id="test1" name="test1" value="123">
<input id="test2" name="test2" placeholder="" value="123">
<input id="test3" name="test3" placeholder="Some Placeholder" value="123">
<input id="test4" name="test4" placeholder="Another placeholder" value="">

CSS-Tricks: https://css-tricks.com/almanac/selectors/p/placeholder-shown/ CanIUse: https://caniuse.com/#feat=css-placeholder-shown
(翻译:CSS-Tricks: https://css-tricks.com/almanac/selectors/p/placeholder-shown/ CanIUse: https://caniuse.com/#feat=css-placeholder-shown

0
required属性添加到输入框中,然后使用:invalid选择显示占位符的输入框。
这在电子邮件等输入类型或带有模式属性的输入框上不起作用。
如果您希望在所有情况下都正常工作,则仍然使用js是最佳选择。

谢谢回复,但所需的方法仅涵盖特定用例,而许多表单不在其中。我正在寻找更少限制的东西。 - Chase

0
const hasPlaceholder = !!input.getAttribute("placeholder") // boolean

2
你的回答可以通过添加更多关于代码的信息以及它如何帮助提问者来改进。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接