IE9中的占位符

时间:2011-06-16 00:53:05

标签: javascript html html5 internet-explorer-9 placeholder

这似乎是一个众所周知的问题,但我在Google上找到的所有解决方案都不适用于我新下载的IE9。

为了在Placeholderinput代码上启用textarea属性,您最喜欢哪种方式?

可选:我在此上失去了很多时间,但尚未找到required属性。你也对此有一些建议吗?显然我可以检查PHP中的值,但是为了帮助用户这个属性非常方便。

11 个答案:

答案 0 :(得分:184)

HTML5占位符jQuery插件
- Mathias BynensHTML5 BoilerplatejsPerf上的合作者)

https://github.com/mathiasbynens/jquery-placeholder

演示&实例

http://mathiasbynens.be/demo/placeholder

<强> P.S
我已经多次使用过这个插件而且它很有效。此外,当您提交表单时, 不会将占位符文本作为值提交(...这是我在其他插件中发现的真正痛苦)。

答案 1 :(得分:21)

我认为这正是您所寻找的:jquery-html5-placeholder-fix

此解决方案使用功能检测(通过modernizr)来确定是否支持占位符。如果没有,添加支持(通过jQuery)。

答案 2 :(得分:17)

如果您想在不使用jquery或modenizer的情况下执行此操作,可以使用以下代码:

(function(){

     "use strict";

     //shim for String's trim function..
     function trim(string){
         return string.trim ? string.trim() : string.replace(/^\s+|\s+$/g, "");
     }

     //returns whether the given element has the given class name..
     function hasClassName(element, className){ 
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return false;
         var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
         return regex.test(element.className);
     }

     function removeClassName(element, className){
         //refactoring of Prototype's function..
         var elClassName = element.className;
         if(!elClassName)
             return;
         element.className = elClassName.replace(
             new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ');
     }

     function addClassName(element, className){
         var elClassName = element.className;
         if(elClassName)
             element.className += " " + className;
         else
             element.className = className;
     }

     //strings to make event attachment x-browser.. 
     var addEvent = document.addEventListener ?
            'addEventListener' : 'attachEvent';
     var eventPrefix = document.addEventListener ? '' : 'on';

     //the class which is added when the placeholder is being used..
     var placeHolderClassName = 'usingPlaceHolder';

     //allows the given textField to use it's placeholder attribute
     //as if it's functionality is supported natively..
     window.placeHolder = function(textField){

         //don't do anything if you get it for free..
         if('placeholder' in document.createElement('input'))
             return;

         //don't do anything if the place holder attribute is not
         //defined or is blank..
         var placeHolder = textField.getAttribute('placeholder');        
         if(!placeHolder)
             return;

         //if it's just the empty string do nothing..
         placeHolder = trim(placeHolder);
         if(placeHolder === '')
             return;

         //called on blur - sets the value to the place holder if it's empty..
         var onBlur = function(){
             if(textField.value !== '') //a space is a valid input..
                 return;
             textField.value = placeHolder;
             addClassName(textField, placeHolderClassName);
         };

         //the blur event..
         textField[addEvent](eventPrefix + 'blur', onBlur, false);

         //the focus event - removes the place holder if required..
         textField[addEvent](eventPrefix + 'focus', function(){
             if(hasClassName(textField, placeHolderClassName)){
                removeClassName(textField, placeHolderClassName);
                textField.value = "";
             }
         }, false);

         //the submit event on the form to which it's associated - if the
         //placeholder is attached set the value to be empty..
         var form = textField.form;
         if(form){
             form[addEvent](eventPrefix + 'submit', function(){
                 if(hasClassName(textField, placeHolderClassName))
                     textField.value = '';
            }, false);
         }

         onBlur(); //call the onBlur to set it initially..
    };

}());

对于您想要使用它的每个文本字段,您需要运行placeHolder(HTMLInputElement),但我想您可以改变它以适应!另外,这样做,而不仅仅是加载意味着你可以使它适用于页面加载时不在DOM中的输入。

请注意,这可以通过将类usingPlaceHolder应用于input元素来实现,因此您可以使用它来设置样式(例如,添加规则.usingPlaceHolder { color: #999; font-style: italic; }以使其看起来更好)。

答案 3 :(得分:8)

这是一个更好的解决方案。 http://bavotasan.com/2011/html5-placeholder-jquery-fix/ 我已经采用了它,只适用于IE10下的浏览器

<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie10 lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie10 lt-ie9" lang="en"> <![endif]-->
<!--[if IE 9]><html class="no-js lt-ie10" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]-->

    <script>
    // Placeholder fix for IE
      $('.lt-ie10 [placeholder]').focus(function() {
        var i = $(this);
        if(i.val() == i.attr('placeholder')) {
          i.val('').removeClass('placeholder');
          if(i.hasClass('password')) {
            i.removeClass('password');
            this.type='password';
          }     
        }
      }).blur(function() {
        var i = $(this);  
        if(i.val() == '' || i.val() == i.attr('placeholder')) {
          if(this.type=='password') {
            i.addClass('password');
            this.type='text';
          }
          i.addClass('placeholder').val(i.attr('placeholder'));
        }
      }).blur().parents('form').submit(function() {
        //if($(this).validationEngine('validate')) { // If using validationEngine
          $(this).find('[placeholder]').each(function() {
            var i = $(this);
            if(i.val() == i.attr('placeholder'))
              i.val('');
              i.removeClass('placeholder');

          })
        //}
      });
    </script>
    ...
    </html>

答案 4 :(得分:5)

如果您想输入说明,可以使用此功能。这适用于IE 9和所有其他浏览器。

<input type="text" onclick="if(this.value=='CVC2: '){this.value='';}" onblur="if(this.value==''){this.value='CVC2: ';}" value="CVC2: "/>

答案 5 :(得分:2)

使用mordernizr检测不支持Placeholder的浏览器,我创建了这个短代码来修复它们。

//If placeholder is not supported
if (!Modernizr.input.placeholder){ 

    //Loops on inputs and place the placeholder attribute
    //in the textbox.
    $("input[type=text]").each( function() { 
       $(this).val($(this).attr('placeholder')); 
    })
}

答案 6 :(得分:2)

我知道我迟到但我找到了一个解决方案:#/ p>

<meta http-equiv="X-UA-Compatible" content="IE=edge"/> <!--FIX jQuery INTERNET EXPLORER-->

答案 7 :(得分:1)

使其在IE-9中使用以下。它适用于我

JQuery需要包括:

jQuery(function() {
   jQuery.support.placeholder = false;
   webkit_type = document.createElement('input');
   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
   $(function() {

     if(!$.support.placeholder) {

       var active = document.activeElement;

       $(':text, textarea, :password').focus(function () {

       if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&         ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
          $(this).val('').removeClass('hasPlaceholder');
        }
      }).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) &&  ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() ==   $(this).attr('placeholder'))) {
     $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});

$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
     $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});

CSS样式需要包括:

.hasPlaceholder {color: #aaa;}

答案 8 :(得分:1)

派对有点晚了,但是我使用了我已经尝试过且值得信赖的JS,它充分利用了Modernizr。可以复制/粘贴并应用于任何项目。每次都有效:

// Placeholder fallback
if(!Modernizr.input.placeholder){

    $('[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();
    $('[placeholder]').parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

}

答案 9 :(得分:0)

我通常认为http://cdnjs.com/非常重要,他们列出了:

//cdnjs.cloudflare.com/ajax/libs/placeholder-shiv/0.2/placeholder-shiv.js

不确定是谁的代码但看起来很简单:

document.observe('dom:loaded', function(){
  var _test = document.createElement('input');
  if( ! ('placeholder' in _test) ){
    //we are in the presence of a less-capable browser
    $$('*[placeholder]').each(function(elm){
      if($F(elm) == ''){
        var originalColor = elm.getStyle('color');
        var hint = elm.readAttribute('placeholder');
        elm.setStyle('color:gray').setValue(hint);
        elm.observe('focus',function(evt){
          if($F(this) == hint){
            this.clear().setStyle({color: originalColor});
          }
        });
        elm.observe('blur', function(evt){
          if($F(this) == ''){
            this.setValue(hint).setStyle('color:gray');
          }
        });
      }
    }).first().up('form').observe('submit', function(evt){
      evt.stop();
      this.select('*[placeholder]').each(function(elm){
        if($F(elm) == elm.readAttribute('placeholder')) elm.clear();
      });
      this.submit();
    });
  }
});

答案 10 :(得分:0)

我在互联网上搜索并找到了一个简单的jquery代码来处理这个问题。在我这边,它已经解决并开始工作,即9。

$("input[placeholder]").each(function () {
        var $this = $(this);
        if($this.val() == ""){
            $this.val($this.attr("placeholder")).focus(function(){
                if($this.val() == $this.attr("placeholder")) {
                    $this.val("");
                }
            }).blur(function(){
                if($this.val() == "") {
                    $this.val($this.attr("placeholder"));
                }
            });
        }
    });