【问题标题】:Can I preserve placeholder if the user select the input text, and the input value is empty string?如果用户选择输入文本并且输入值为空字符串,我可以保留占位符吗?
【发布时间】:2011-08-15 22:10:30
【问题描述】:

输入可以设置占位符,但是如果用户专注于该输入,占位符就会消失,我该如何关闭占位符,使用用户开始类型少于一个字符?谢谢。

【问题讨论】:

    标签: javascript jquery css placeholder


    【解决方案1】:

    使用placeholder 属性,你不能。

    【讨论】:

      【解决方案2】:

      不具有默认行为。但是,您可以通过在组合中添加一些 JS 来做到这一点

      现场小提琴:http://jsfiddle.net/jomanlk/gPBhX/

      <input type='text' class='placeholder' data-title='hello'>
      
      $('.placeholder').each(function(){
          $(this).data('placeholder', $(this).attr('data-title'));
          $(this).val($(this).attr('data-title'));
      });
      
      $('.placeholder').live('keydown', function(){
          if ($(this).val() == $(this).data('placeholder')) {
              $(this).val('');         
          } 
      });
      
      $('.placeholder').live('blur', function(){
          if ($(this).val().trim() == '') {
              $(this).val($(this).data('placeholder'));
          }
      });
      

      注意:有一个限制,如果用户将一些文本粘贴到框中,它不会清除,但您也可以通过绑定到更改事件来轻松解决这个问题。这只是一个演示

      【讨论】:

        猜你喜欢
        • 2018-04-10
        • 2013-05-02
        • 1970-01-01
        • 2018-03-14
        • 2021-08-12
        • 2013-10-31
        • 2014-08-25
        • 2015-09-20
        • 2023-03-12
        相关资源
        最近更新 更多