IE兼容实现HTML5的placeholder

一、JQ方式实现(不支持password类型)



<script type="text/javascript">   
  if( !('placeholder' in document.createElement('input')) ){   
    $('input[placeholder],textarea[placeholder]').each(function(){    
      var that = $(this),    
      text= that.attr('placeholder');    
      if(that.val()===""){    
        that.val(text).addClass('placeholder');    
      }    
      that.focus(function(){    
        if(that.val()===text){    
          that.val("").removeClass('placeholder');    
        }    
      })    
      .blur(function(){    
        if(that.val()===""){    
          that.val(text).addClass('placeholder');    
        }    
      })    
      .closest('form').submit(function(){    
        if(that.val() === text){    
          that.val('');    
        }    
      });    
    });    
  }   </script>
上面的方法缺点就是不能支持password类型的文本框,目前还没有很好的解决办法。

二、使用JQ插件jquery.placeholer.js

Github地址:https://github.com/tonitech/jquery.placeholder.js 引入到页面然后执行下面的代码:



<script type="text/javascript">$(function() {
 $('input, textarea').placeholder();});</script>
这个方法比较简单,唯一令我不喜欢的是它要求jquery版本1.3到1.8,而我现在在项目中使用的是1.11,所以无奈我没有使用,如果你的项目使用的是1.3-1.8版本的,可以尝试下。

三、原生JS通过Label标签实现



<script type="text/javascript">var funPlaceholder = function(element) {  
    //检测是否需要模拟placeholder  
    var placeholder = '';  
    if (element && !("placeholder" in document.createElement("input")) && (placeholder = element.getAttribute("placeholder"))) {  
        //当前文本控件是否有id, 没有则创建  
        var idLabel = element.id ;  
        if (!idLabel) {  
            idLabel = "placeholder_" + new Date().getTime();  
            element.id = idLabel;  
        }  
        //创建label元素  
        var eleLabel = document.createElement("label");  
        eleLabel.htmlFor = idLabel;  
        eleLabel.style.position = "absolute";  
        //根据文本框实际尺寸修改这里的margin值  
        eleLabel.style.margin = "8px 0 0 3px";  
        eleLabel.style.color = "graytext";  
        eleLabel.style.cursor = "text";  
        //插入创建的label元素节点  
        element.parentNode.insertBefore(eleLabel, element);  
        //事件  
        element.onfocus = function() {  
            eleLabel.innerHTML = "";  
        };  
        element.onblur = function() {  
            if (this.value === "") {  
                eleLabel.innerHTML = placeholder;  
            }  
        };  
        //样式初始化  
        if (element.value === "") {  
            eleLabel.innerHTML = placeholder;  
        }  
    }  };  funPlaceholder(document.getElementsByName("username")[0]);  funPlaceholder(document.getElementsByName("password")[0]);  </script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值