【问题标题】:User clicks in an input field and the value disappear用户单击输入字段,值消失
【发布时间】:2015-09-02 15:41:17
【问题描述】:

我搜索脚本以使输入字段中的值消失。 用户点击进去,值就会消失,如果用户没有在输入字段中写入内容,它应该会再次出现文本。

我尝试使用 jQuery 和 focusin() focusout() 但随后我更改了所有输入字段的值。

【问题讨论】:

  • 也许你可以向用户展示你到底尝试了什么?
  • 使用placeholder="Your default value"?
  • 你可以这样尝试...

标签: javascript jquery html


【解决方案1】:

我打赌你正在寻找 HTML5 属性 placeholder 提供的机制,就这样使用它:

<input type="text" placeholder="This value will disappear" name="somename" value="" />

至于textarea的多行占位符,检查这个方法:

https://stackoverflow.com/a/25261886/1477938

【讨论】:

  • @AlexKante The placeholder can't make breaks in the text of the value. 是什么意思?
【解决方案2】:

您可以为此使用占位符,或者您可以使用值作为占位符。看看就好了

Placeholder based Value

jQuery(document).ready(function(){
    jQuery("input[type='text']").each(function(){
        var x = jQuery(this).attr("value");
        jQuery(this).focus(function(){
            if($(this).val()==x)
            {
                $(this).val('');
            }       
        });
        jQuery(this).blur(function(){
            if($(this).val()=="")
            {
                $(this).val(x);
            }
        });
    });
});

使用占位符

<input type="text" placeholder="test">

【讨论】:

    【解决方案3】:

    您可以使用占位符属性。

    $(document).ready(function() {
      $('#input').focus(
        function() {
          if (!$(this).val().length || $(this).val() == $(this).data('placeholder')) {
            $(this).val('');
          }
        }
      );
    
      $('#input').blur(
        function() {
          if (!$(this).val().length) {
            $(this).val($(this).data('placeholder'));
          }
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" placeholder="Text here" />
    <br/>
    <hr/>
    
    <b>ALTERNATIVE (jQuery):</b>
    <br/>
    
    <input type="text" id="input" data-placeholder="Text here" value="Text here" />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多