微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

让脑残的IE兼容实现HTML5的placeholder

只要用过表单中的placeholder的前端同学,就会发现它的强大之处,再也不用写一些超多事件的JS来实现,而这个属性却不能被脑残的IE低版本所支持,我们只能想一些办法来变通一下。

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


<script type="text/javascript">   
  if( !('placeholder' in document.createElement('input'))){   
    $'input[placeholder],textarea[placeholder]').each(function(){    
      var that = $(this),    
      text thatattr'placeholder');thatval()===""    
        thattextaddClass    
      }    
      thatfocus    
        ()===    
          thatremoveClass    
        })blurclosest'form'submit()=== text''});    
        
     </script>

上面的方法缺点就是不能支持password类型的文本框,目前还没有很好的解决办法。

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

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

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

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

funPlaceholder element) //检测是否需要模拟placeholder placeholder ; ifelement &&"placeholder""input"placeholder elementgetAttribute"placeholder"))) //当前文本控件是否有id,没有则创建 idLabel id (!idLabel idLabel "placeholder_"+new Date().getTime element idLabel //创建label元素 eleLabel document"label" eleLabelhtmlFor styleposition "absolute"//根据文本框实际尺寸修改这里的margin值 eleLabelmargin "8px 0 0 3px"color "graytext"cursor "text"//插入创建的label元素节点 elementparentNodeinsertBeforeeleLabel,161);">//事件 onfocus eleLabelinnerHTML }; elementonblur thisvalue eleLabel placeholder //样式初始化 funPlaceholderdocumentgetElementsByName"username")[0]);"password"这个方法我现在在用,而且还是原生的,感觉很不错,推荐给大家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。