【问题标题】:disappearing and reappearing of text in textbox文本框中的文本消失和重新出现
【发布时间】:2013-02-28 18:02:27
【问题描述】:
<asp:TextBox ID="TextBox2" runat="server" value="Your Text here" onfocus=" this.value = '';" onblur="if(this.value == '') ****{ this.value='?????'; }****"></asp:TextBox>

当我单击文本框时,我希望文本框中的文本消失,我可以通过我使用过的 onfocus 实现....

但是,当文本框为空时,我希望出现之前输入的值,如果是第一次,即如果我之前没有输入任何文本,那么应该出现默认值(“您的文本”)。

例如:我第一次单击文本框并输入值“80”,然后再次单击文本框,内部的值应该清除,如果我没有输入任何值并单击外部然后'80' 应该显示在文本框中,而不是 'Your Text here'。

谢谢你。

【问题讨论】:

标签: c# javascript jquery asp.net visual-studio-2010


【解决方案1】:

如果您的浏览器支持 HTML5:

<input type="text" placeholder="Your Text here" />

如果你想为默认不支持的浏览器支持占位符属性,这里有一个 javascript 后备:

$('[placeholder]').focus(function() {
   var input = $(this);
   if (input.val() == input.attr('placeholder')) {
       input.val('');
       input.removeClass('placeholder');
   }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur();

【讨论】:

  • 当我单击文本框时,该值不会被清除,如果文本框为空,则不会显示以前的值,而是仅显示默认占位符值
【解决方案2】:

你可以像这个例子那样做。声明一个全局变量,将当前值设为 blur 时的值,点击时将其设为 null,如果当前输入为 null,则重新赋值。

<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.3.1');
</script>
<body>
    <input type="text" value="Your text here" id="test" onclick="clicked();" onblur="outted();">
    <script>
    var pre_value = '';
    function clicked(){ pre_value = $('#test').val(); $('#test').val('');}

    function outted(){ if($('#test').val() == '') $('#test').val(pre_value); }
    </script>
</body>

希望对你有帮助

【讨论】:

  • 你能告诉我一个不使用 google.load 的替代方案吗...一个没有使用 google.load 函数的简单 jQuery 脚本
  • @ashutosh:代码不需要 google.load。普通的 jquery 包含将起作用。我添加它以使其独立。您可以删除 "" 而是添加通常的 jquery 脚本包含。
猜你喜欢
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多