【问题标题】:Detect if input placeholder is visible检测输入占位符是否可见
【发布时间】:2016-05-24 23:07:18
【问题描述】:

我正在尝试寻找一种方法来检测输入当前是否显示占位符。

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

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

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

【问题讨论】:

    标签: javascript jquery placeholder


    【解决方案1】:

    首先查看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="">

    【讨论】:

      【解决方案2】:

      现在,对于大多数浏览器,我们可以使用: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

      【讨论】:

        【解决方案3】:

        required 属性添加到输入,然后使用:invalid 选择显示占位符的输入。

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

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

        【讨论】:

        • 感谢您的回复,但是所需的方法只涵盖了具体的用例,很多表格都不属于这个范围。我正在寻找不受限制的东西。
        猜你喜欢
        • 1970-01-01
        • 2011-07-02
        • 2018-04-10
        • 1970-01-01
        • 2020-12-09
        • 2013-10-31
        • 1970-01-01
        • 2013-07-07
        • 1970-01-01
        相关资源
        最近更新 更多