【问题标题】:emptyText in HTMLHTML 中的空文本
【发布时间】:2012-10-26 18:48:21
【问题描述】:

有没有办法像在 ExtJS 中那样在输入字段中添加类似于 emptyText 的内容?

我尝试使用更改的 CSS 设置值。但是,该值与表单一起提交,并且在我单击输入字段后它并没有消失。我需要支持IE7及以上

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html extjs


    【解决方案1】:

    你要找的是placeholder..W3School

    <input type="text" placeholder="Hii" />
    

    您可以找到适用于 ie 和其他不支持占位符的旧版本浏览器的 polyfills..

    您可以为不支持占位符的浏览器添加此代码,使其工作方式与在良好浏览器中的工作方式相同..*它需要 JQuery

    // This adds 'placeholder' to the items listed in the jQuery .support object. 
    jQuery(function() {
       jQuery.support.placeholder = false;
       test = document.createElement('input');
       if('placeholder' in test) jQuery.support.placeholder = true;
    });
    
    
    // This adds placeholder support to browsers that wouldn't otherwise support it. 
    $(function() {
       if(!$.support.placeholder) { 
          var active = document.activeElement;
          $(':text').focus(function () {
             if ($(this).attr('placeholder') != '' && $(this).attr('placeholder') != undefined && $(this).val() == $(this).attr('placeholder')) {
                $(this).val('').removeClass('hasPlaceholder');
             }
          }).blur(function () {
             if ($(this).attr('placeholder') != '' && $(this).attr('placeholder') != undefined && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
                $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
             }
          });
          $(':text').blur();
          $(active).focus();
          $('form:eq(0)').submit(function () {
             $(':text.hasPlaceholder').val('');
          });
       }
    });
    

    【讨论】:

    • 这适用于哪个浏览器?我正在使用 IE,但没有看到任何 emptyText/占位符文本。检查这个jsfiddle.net/dFpzq
    • 这在IE10及更好的版本中有效,在IE9及以下版本中无效
    • 是的。刚刚检查了该链接:(不幸的是,我在 IE 7 及更高版本中需要它:(
    • @hop,网上有很多添加IE7+支持的脚本。
    【解决方案2】:

    Rajat 的答案是正确的,但仅适用于 HTML5。 如果您想要一个适用于 IE(和其他浏览器)的答案仅使用纯 javascript 而没有任何库,您可以查看 this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多