检测输入占位符是否可见

时间:2016-02-13 21:41:46

标签: javascript jquery placeholder

我试图找到一种方法来检测输入当前是否显示占位符。

我知道我们可以测试某个浏览器是否支持占位符,我会使用它,但这不是我在这里要求的。

:placeholder-shown伪类完全符合我的需要,但对它的支持非常低。远低于对占位符的支持。所以我正在寻找另一种方法。

注意:解决方案不能依赖于输入是否已更改或获得值。自动填充输入既没有技术价值,也没有变化。因此,解决方案需要真正检测它自己的占位符。

3 个答案:

答案 0 :(得分:2)

首先,检查元素是否正在使用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="">

答案 1 :(得分:1)

LINE_NUMBER=`grep -o -n TERMINATE $OSCAM_LOG|tail -n 1|sed "s/:/ \\'/g"|awk -F" " '{print $1}'` tail -n +$LINE_NUMBER $YOUR_FILE_NAME 属性添加到输入中,然后使用required选择显示占位符的输入。

这不适用于电子邮件等输入类型或带有模式属性的输入。

如果您希望js在所有情况下都能正常工作,那么使用js仍然是最佳选择。

答案 2 :(得分:1)

如今,对于大多数浏览器,我们可以使用: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技巧:https://css-tricks.com/almanac/selectors/p/placeholder-shown/

我可以使用:https://caniuse.com/#feat=css-placeholder-shown