让IE支持placeholder属性

Love The Way You Lie 2022-08-19 02:15 408阅读 0赞

placeholder 属性提供可描述输入字段预期值的提示信息
该提示会在输入字段为空时显示,并会在字段获得焦点时消失。
但placeholder不支持IE10以下版本
在页面中只需引入placeholder.js即可

  1. /* * jQuery placeholder, fix for IE6,7,8,9 * @website itmyhome.com */
  2. var JPlaceHolder = {
  3. //检测
  4. _check : function(){
  5. return 'placeholder' in document.createElement('input');
  6. },
  7. //初始化
  8. init : function(){
  9. if(!this._check()){
  10. this.fix();
  11. }
  12. },
  13. //修复
  14. fix : function(){
  15. jQuery(':input[placeholder]').each(function(index, element) {
  16. var self = $(this), txt = self.attr('placeholder');
  17. self.wrap($('<div></div>').css({position:'relative', zoom:'1', border:'none', background:'none', padding:'none', margin:'none'}));
  18. var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css('padding-left');
  19. var holder = $('<span></span>').text(txt).css({position:'absolute', left:pos.left, top:pos.top, height:h, lienHeight:h, paddingLeft:paddingleft, color:'#aaa'}).appendTo(self.parent());
  20. self.focusin(function(e) {
  21. holder.hide();
  22. }).focusout(function(e) {
  23. if(!self.val()){
  24. holder.show();
  25. }
  26. });
  27. holder.click(function(e) {
  28. holder.hide();
  29. self.focus();
  30. });
  31. });
  32. }
  33. };
  34. //执行
  35. jQuery(function(){
  36. JPlaceHolder.init();
  37. });

使用方法:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>IE支持placeholder</title>
  5. <script type="text/javascript" src="jquery.min.js"></script>
  6. <script type="text/javascript" src="placeholder.js"></script>
  7. </head>
  8. <body>
  9. <table>
  10. <tbody>
  11. <tr>
  12. <td> <input type="text" name="username" placeholder="Username" /> </td>
  13. </tr>
  14. <tr>
  15. <td> <input type="password" name="password" placeholder="Password" /> </td>
  16. </tr>
  17. </tbody>
  18. </table>
  19. </body>
  20. </html>

如果要修改placeholder内的文字样式 可在placeholder.js里<span></span>中添加style属性,如:

  1. <span style="font-size: 13px;padding-top: 8px;"></span>

这样在IE中就会显示正常

这里写图片描述这里写图片描述

因为本例中的input文本框使用了bootstrap 所以行高会高一点,如果是普通的input 则无需添加style属性

演示:ie-placeholder

作者:itmyhome

发表评论

表情:
评论列表 (有 0 条评论,408人围观)

还没有评论,来说两句吧...

相关阅读

    相关 IE支持HTML5

    HTML5能为我们做的事儿很多,最为可口的就是语义化标签的应用,如果你已经在Chrome或者其他支持HTML5的浏览器上用过它,那这篇文章对你一定有用,因为现在你也可以在IE上