HTML中的emptyText

时间:2012-11-06 18:51:58

标签: javascript html extjs

有没有办法在输入字段中使用与ExtJS类似的emptyText?

我尝试使用更改的CSS设置值。但是,该值随表单一起提交,并且一旦单击输入字段,它就不会消失。我需要支持IE7及以上版本

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:3)

您要找的是placeholder .. W3School

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

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

您可以为不支持占位符的浏览器添加此代码,使其在良好的浏览器中工作方式相同。*它需要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('');
      });
   }
});

答案 1 :(得分:2)

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