IE兼容实现HTML5的placeholder

来源:互联网 发布:辽宁省软件协会官网 编辑:程序博客网 时间:2024/05/22 07:03
一、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.jsGithub地址: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 0