ie上如何兼容placeholder

首先,判断浏览器是否支持placeholder属性:

var input = document.createElement('input');
if("placeholder" in input){
    alert('支持');
}else{
    alert('不支持');
}

 

(1)如果只需要让不支持placeholder的浏览器能够支持改功能,并不要求支持原生placeholder的浏览器表现一致,那么可以采用如下方法:

Placeholder在不支持html5的低版本的浏览器中,placeholder属性是无效的,非现代浏览器( 例如 IE6-IE9 )是不支持placeholder属性的
 function placeholder(nodes,pcolor) {
      if(nodes.length && !("placeholder" in document_createElement_x("input"))){
          for(i=0;i
              var self = nodes[i],
                  placeholder = self.getAttribute('placeholder') || '';     
              self.onfocus = function(){
                  if(self.value == placeholder){
                     self.value = '';
                     self.style.color = "";
                  }               
              }
              self.onblur = function(){
                  if(self.value == ''){
                      self.value = placeholder;
                      self.style.color = pcolor;
                  }              
              }                                       
              self.value = placeholder;  
              self.style.color = pcolor;              
          }
      }
    }    

(2)如果需要自定义样式,并且希望placeholder在所有浏览器下表现一致,可以通过利用label标签模拟一个placeholder的样式放到输入框上,当输入框获得焦点的时候,隐藏label,当输入框失去焦点的时候,显示label。 或者是在input上应用背景图片,获得和失去焦点的时候切换背景图片是否显示。

<script>
$(function(){
    $('.for_text').click(function(){
        $('.text').focus()
    })
    $('.text').blur(function(){
        $('.for_text').hide();
    })
})
</script>
<style>
.for_text{ position:absolute; cursor:text; margin:5px; color:#999;}
.text{ padding:5px;}
</style>
<form>
<label for="text" class="for_text">请输入文本</label>
<input type="text" name="text" class="text"/>
</form>

 

(3)jquery解决方案:

jQuery('[placeholder]').focus(function() {
  var input = jQuery(this);
  if (input.val() == input.attr('placeholder')) {
    input.val('');
    input.removeClass('placeholder');
  }
}).blur(function() {
  var input = jQuery(this);
  if (input.val() == '' || input.val() == input.attr('placeholder')) {
    input.addClass('placeholder');
    input.val(input.attr('placeholder'));
  }
}).blur().parents('form').submit(function() {
  jQuery(this).find('[placeholder]').each(function() {
    var input = jQuery(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
    }
  })
});

(4)最后一种方法,也是使用最常见的,但是不能改变文本的颜色,使用脚本的方式判断文本框的值,获取焦点或者输入文本的时候,如果为预设的值,那么就清空文本框,失去焦点的时候,如果文本框的值为空,则替换为我们预设的值。

<input type="text" name="text" value="请输入文本" class="text"
onFocus="if(this.value=='请输入文本') this.value = ''"
onBlur="if(this.value=='') this.value='请输入文本'"
/>

拓展:

想改变Placeholder文字的颜色,并不想改变输入文字的颜色。正确的写法如下:

::-moz-placeholder{color:red;}              //Firefox
::-webkit-input-placeholder{color:red;}     //Chrome,Safari
:-ms-input-placeholder{color:red;}          //IE10

 

posted @ 2016-12-02 11:33  最爱小虾  阅读(14584)  评论(0编辑  收藏  举报