让IE支持placeholder属性,跨浏览器placehoder

在html5中,文本框,也就是input, type为text,或者password,新增了一个属性placeholder,也就是占位符,以下是firefox浏览器下的表现形式,当输入的时候,占位符就会消失。这个属性非常好用,因为有这个必要html5才会因素这个属性,然而在IE下,就没有这效果,以下是IE9的表现。

下面是JS版:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>跨浏览器placehoder</title>
<meta name="author" content="ifrans.cn" />
<meta name="description" content="跨浏览器的placehoder原生js版,让ie也支持placehoder" />
<meta name="keywords" content="跨浏览器,placehoder,ie,原生js,表单" />
<style>
body{font:12px/1.5 Arial,"\5b8b\4f53", sans-serif;-webkit-text-size-adjust:100%;color:#333333;background:white;}
h1,h2,h3,h4,h5,h6,button,input,select,textarea{font-size:100%; font-weight:normal; font-style:normal;}
table{border-collapse:collapse;border-spacing:0;font-size:100%;font:inherit;empty-cells:show}
fieldset,img{border:0;}
address,caption,cite,code,dfn,th,var{font-style:normal; font-weight:normal;}
button,input,select,textarea{font-family:Arial, Helvetica, sans-serif;text-decoration: none;outline:none;-moz-outline:none;font-size:100%;}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{vertical-align:middle;-webkit-appearance:button;cursor:pointer;}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none;}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}
textarea{resize:none;overflow:auto;vertical-align:top}
ul,ol,li,dl{list-style-type:none;}         i,em{font-style:normal}     svg:not(:root){overflow:hidden}
img{vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;-webkit-tap-highlight-color:rgba(0,0,0,0);}   
a{color:#333;text-decoration: none;outline:none;} 
a:link {color:#333;} 
a:visited {color:#333;} 
a:hover {color:#c00;text-decoration:underline;}
a:active{blr:expression(this.onFocus=this.blur())}
a:focus {outline:none;-moz-outline:none;}
form{ width:300px;  margin:20px auto 0;}
h3{ font-weight:bold; margin:10px 0;}
p{ margin-bottom:10px;}
input{ vertical-align:middle; margin-left:10px; height:24px; line-height:24px; width:200px; padding-left:2px; border:1px #CCC solid;}
textarea{ vertical-align:middle; margin-left:10px; width:200px; height:50px; font:inherit; padding-left:2px; border:1px #CCC solid;}
.wrap-statistics{ visibility:hidden;}
.dn{ display:none;}   .db{ display:block;}
.finps{ width:200px; height:24px;line-height:24px; border:1px #C30 solid; padding:0 5px; color:#000;}
.oinps{width:200px; height:24px;line-height:24px; border:1px #CCC solid; padding:0 5px; color:#000;z-index:5;}
.ftext{ width:200px; height:50px; border:1px #C30 solid; padding:0 5px; color:#000;}
.otext{width:200px; height:50px; border:1px #CCC solid; padding:0 5px; color:#000;}
</style>
</head>
<body>
<form id="form1">
    <h3>通过input方式模拟placeholder</h3>
    <p><label for="username1">用户名:</label><input type="text" name="username1" class="tst oinps"  placeholder="请输入用户名" value="123" ></p>
    <p><label for="password1">密 码:</label><input type="password" name="password1" class="tst oinps" placeholder="请输入密码" value="" ></p>
    <p><label for="address1">地 址:</label><input type="text" name="address1"  placeholder="请输入地址" value="" ></p>
</form>
<form id="form2">
    <h3>通过textarea方式模拟placeholder</h3>
    <p><label for="remarks1">备 注:</label><textarea placeholder="请输入备注"  class="otext" id="remarks1"></textarea></p>
    <p><label for="remarks2">备 注:</label><textarea placeholder="请输入备注" class="otext" id="remarks2"></textarea></p>
    <p><label for="remarks3">备 注:</label><textarea id="remarks3"></textarea></p>
</form>
<script>
/**
 * @name placeHolder
 * @class 跨浏览器placeHolder,对于不支持原生placeHolder的浏览器,通过value或插入span元素两种方案模拟
 * @param {Object} obj 要应用placeHolder的表单元素对象  
 */
function readyplace(element, type, handler){
 if (element.addEventListener){
  element.addEventListener(type, handler, false);
 } else if (element.attachEvent){
  element.attachEvent("on" + type, handler);
 } else {
  element["on" + type] = handler;
 }
}
(function (window, undefined) {
var hasClass = function(elem,sClass)
{
    var sOldName=elem.className;
    if(sOldName)
    {
        sOldName=sOldName.split(' ');
        for(var i=0;i<sOldName.length;i++)
        {
            if(sOldName[i]==sClass)
            {
                return true;
            }
        }
    }
}
var addClass = function(elem,sClass)
{
    if(!hasClass(elem,sClass))
    {
        if(elem.className)
        {
            var sOldName=elem.className, blank = (sOldName != '') ? ' ' : '';
            elem.className=sOldName + blank + sClass;
        }
        else
        {
            elem.className=sClass;
        }
    }
}
var removeClass = function(elem,sClass)
{
    var sOldName=elem.className.split(' ');
    var sNewClass='';
    for(var i=0;i<sOldName.length;i++)
    {
        if(sOldName[i] && sOldName[i]!=sClass)
        {
            sNewClass+=sOldName[i]+' ';
        }
    }
    elem.className=sNewClass.replace(/(^\s+)|(\s+$)/g, '');
}
 var Place = (function() {
  return function(set){
   this.tagName    = set.tagName || "input" ;  
   this.placeattr  = set.placeattr || "placeholder" ;     
   this.isempty    = set.isempty ? true : false;
   this.focusCls   = set.focusCls || "finps";
   this.onblurCls  = set.onblurCls || "oinps";
   this.init();
  } 
    })();
 Place.prototype = {
  init : function() { 
   var elemTagName = document.getElementsByTagName(this.tagName);
   for(var i=0;i<elemTagName.length;i++){
    this.create(elemTagName[i],this.isempty);
   }  
  },
  create:function(obj,isShow){
   if (!obj.getAttribute(this.placeattr)) return;
   var getStyle = function(obj, prop) {
    if (obj.currentStyle) { //IE浏览器
     return obj.currentStyle[prop];
    } else if (window.getComputedStyle) { //W3C标准浏览器
     return document.defaultView.getComputedStyle(obj, null)[prop];
    }
    return null;
   };
   var defaultValue = obj.getAttribute(this.placeattr);
   var placeHolderCont = document.createTextNode(defaultValue);
   var REPX=/px|em|rem/;
   var pat=parseInt(getStyle(obj,"paddingTop").replace(REPX,'')) || 0;
   var par=parseInt(getStyle(obj,"paddingRight").replace(REPX,'')) || 0;
   var pab=parseInt(getStyle(obj,"paddingBottom").replace(REPX,'')) || 0;
   var pal=parseInt(getStyle(obj,"paddingLeft").replace(REPX,'')) || 0;
   
   var mat=parseInt(getStyle(obj,"marginTop").replace(REPX,'')) || 0;
   var mar=parseInt(getStyle(obj,"marginRight").replace(REPX,'')) || 0;
   var mab=parseInt(getStyle(obj,"marginBottom").replace(REPX,'')) || 0;
   var mal=parseInt(getStyle(obj,"marginLeft").replace(REPX,'')) || 0;
   
   var fontSize = getStyle(obj, 'fontSize');
   if (!obj.getAttribute("id")) {
    var idFor = "place" +Math.floor(Math.random().toString().substr(2,8));
   }else{
    var idFor =obj.getAttribute("id");
   }
   obj.setAttribute("id", idFor);
            var LabelWrap = document.createElement('label');
       LabelWrap.setAttribute("for", idFor);
       LabelWrap.className = 'placewrap';
                LabelWrap.style.cssText = 'font-size:'+fontSize+';position:absolute;cursor:text;text-indent:2px;z-index:5;top:'+mat+'px;left:'+mal+'px;padding:'+pat+'px '+par+'px '+pab+'px '+pal+'px;color:#A9A9A9;';
    LabelWrap.style.width = obj.offsetWidth - (parseInt(getStyle(obj, 'marginLeft'), 10)||0) + 'px';
    LabelWrap.style.lineHeight = obj.nodeName.toLowerCase() == 'textarea' ? '': obj.offsetHeight-pat-pab + 'px';
   var placebox=document.createElement("div");
    placebox.className="labelwraps";
    placebox.style.cssText='position:relative;visibility:visible;z-index:1;display:inline-block;';
    obj.parentNode.insertBefore(placebox,null);
    LabelWrap.appendChild(placeHolderCont);
    placebox.appendChild(LabelWrap); 
    placebox.appendChild(obj); 
    obj.removeAttribute(this.placeattr);
            LabelWrap.onclick = function() { obj.focus();  };
   LabelWrap.style.display = obj.value == '' ? 'block': 'none';
   var changeHandler = function() {
    LabelWrap.style.display = obj.value != '' ? 'none': 'block';
   };
            var that=this;
   if(!isShow){
    obj.onclick = function() {
     if(obj.value == defaultValue && obj.value != ''){
      LabelWrap.style.display ='block';
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }else {
      LabelWrap.style.display ='none';
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }
    }
    obj.oninput = function() {
     if(obj.value != ''){
      LabelWrap.style.display ='none';
     }else{
      LabelWrap.style.display ='block';
     } 
    }
    obj.onblur = function() {
     if(obj.value != ''){
      LabelWrap.style.display ='none';
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }else{
      LabelWrap.style.display ='block';
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }
    }
    //obj.onblur();
   }else{
    obj.onclick = function() {
     if(obj.value == defaultValue && obj.value != ''){
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }else {
      removeClass(obj,that.onblurCls);
                        addClass(obj,that.focusCls);
     }
    };
    obj.onblur = function() {
     if(obj.value != ''){
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }else{
      removeClass(obj,that.focusCls);
      addClass(obj,that.onblurCls);
     }
    };
    if (typeof(obj.oninput) == 'object') {
     obj.addEventListener("input", changeHandler, false);
    } else {
     obj.onpropertychange = changeHandler;
    }
   };
   return this;
  }
 }
 var placeholder = function(options) { new Place(options); }
 window.placeholder = placeholder;
 return placeholder;
})(window);
readyplace(document, 'readystatechange', function(){
    placeholder({focusCls:'finps',onblurCls:'oinps',isempty:false});
 placeholder({tagName:'textarea',focusCls:'ftext',onblurCls:'otext',isempty:true});
})
</script>
</body>
</html>

你可能感兴趣的:(IE,placehoder)