【问题标题】:HTML permanent Placeholder workaroundHTML 永久占位符解决方法
【发布时间】:2012-07-24 07:44:29
【问题描述】:

我在我的应用程序中为输入框使用占位符,并为不支持占位符的浏览器使用 jquery 解决方法。然而,在大多数浏览器中,即使输入为空,占位符也会在输入处于焦点时消失。一种解决方法是在输入字段上使用透明背景,并在输入字段后面直接放置一个带有文本的跨度,并在输入内容后将背景更改为不透明。问题是我的应用程序现在有超过 3000 个输入字段。这是否可以通过运行时的 jquery 插件来做到这一点?或者我愿意接受更好的建议。请帮忙。

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    同一页面上是否有 3000 个输入字段?在这种情况下,您需要以某种方式重新设计您的应用程序。

    如果您在多个页面上有不同的输入,并且希望插件在需要时自动生成占位符,那么有很多不错的插件可以做到这一点。这是一个全面的 polyfill 列表 - 只需查找“Web 表单:输入占位符”标题即可。 https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

    它们中的大多数不需要为每个实例专门调用,因此您应该避免修改 3000 行代码。 :)

    【讨论】:

    • 呃-抱歉。编辑了我的答案。
    【解决方案2】:

    我会使用 value attr 而不是逻辑如下所示。

    var input = document.createElement('input');
    if(! ('placeholder' in input))
    {
        $("input[placeholder]").focus(/* clear value if it is equals placeholder */);
        $("input[placeholder]").blur(/* assign placeholder if it is "" */);
        $("input[placeholder]").each(/* assign placeholder if value equals "" */)
    }
    

    您还可以更改焦点和模糊输入的样式(或类),使其看起来更像占位符。

    【讨论】:

      【解决方案3】:

      这是我写的和正在使用的:

          <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
      <style>
      body{
          background-color:#DDD;
      }
      
      span.placeholder
      {
          background-color:#FFF;
          color:#777;
          border-radius: 4px 4px 4px 4px;
          margin: 5px 0;
          padding: 9px 0 8px 13px;
          width: 297px;
      
      }
      input
      {
          border: 1px solid #707A68;
          border-radius: 4px 4px 4px 4px;
          margin: 5px 0;
          padding: 10px;
          width: 310px;
          background:transparent;
      }
      
      </style>
      
      <body>
      <div>
          <input type="text" placeholder="hello" name="hh"/>
      </div>
      </body>
      
      <script>
      $('input').each(function(){
      
          var txt = $(this).attr('placeholder');
          var name = $(this).attr('name');
          var node = $("<span class='placeholder'>"+txt+"</span>").appendTo($(this).parent());
          $(this).before(node);
          node.css('position','absolute');
          node.css('z-index','-1');
          node.css('display','block');
          $(this).attr('placeholder','');
      });
      $('input').bind('keyup',function(){
          if($(this).val()=="")
              $(this).css('background','transparent');
          else
              $(this).css('background','#FFF');
      });
      </script>
      

      【讨论】:

        猜你喜欢
        • 2019-12-08
        • 2014-11-14
        • 1970-01-01
        • 1970-01-01
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-07
        相关资源
        最近更新 更多