IE8中placeholder兼容问题

  placeholder是HTML5中的一个属性,可以在文本框中设置placeholder属性来显示一些提示性的文字,但对IE10以下的浏览器不支持。在IE8下如果贸然使用placeholder,页面上是无法显示的。效果如下所示:

以下有两种方法解决这个问题:

方法一:在页面中添加下面一段脚本

 1 if( !('placeholder' in document.createElement('input')) ){   
 2 
 3     $('input[placeholder],textarea[placeholder]').each(function(){    
 4       var that = $(this),    
 5       text= that.attr('placeholder');    
 6       if(that.val()===""){    
 7         that.val(text).addClass('placeholder');    
 8       }    
 9       that.focus(function(){    
10         if(that.val()===text){    
11           that.val("").removeClass('placeholder');    
12         }    
13       })    
14       .blur(function(){    
15         if(that.val()===""){    
16           that.val(text).addClass('placeholder');    
17         }    
18       })    
19       .closest('form').submit(function(){    
20         if(that.val() === text){    
21           that.val('');    
22         }    
23       });    
24     });    
25   }   

以上方法也存在缺项,就是上面的方法不能支持password类型的文本框,如下所示:

 

第二种方法:调用jQuery的placeholder插件

  插件的地址:https://github.com/mathiasbynens/jquery-placeholder

  将placeholder.js文件引用到页面,页面中添加下面脚本:

   1 $(function() { 2 $('input, textarea').placeholder(); 3 }); 

  效果如下:

posted @ 2015-12-15 15:50  zhaoheqi  阅读(162)  评论(0编辑  收藏  举报