ie下兼容placeholder
之前找过各种兼容ie下的placeholder,结果都不尽人意,最后看到这种,感觉还是可以的,所以分享给大家;
html:
<div class="login-box">
<h3>用户登录</h3>
<ul>
<li>
<input type="text" name="userName" value="" placeholder="请输入用户名" id="userName" />
</li>
<li>
<input type="password" name="password" value="" placeholder="请输入密码" id="password" />
</li>
</ul>
</div>
css:
*{padding:0px;margin:0px;}
ul li{list-style: none}
.login-box{width:480px;height:240px;background:#f5f5f5;border:1px solid #e0e0e0;border-radius:3px;position: fixed;top:50%;margin-top:-120px;left:50%;margin-left:-240px;z-index:9;}
.login-box h3{height:50px;line-height:50px;text-align:center;font-weight: normal;font-size:20px;color:#666;}
.login-box ul li{width:300px;height:40px;border:1px solid #e0e0e0;border-radius:3px;background:#fff;margin:0px auto 15px;position:relative;}
.login-box ul li input{width:290px;height:18px;padding:10px 0 10px 3px;border:none;outline: none}
js:
function ieInput(obj){
var placeholder="";
if(obj && !('placeholder' in document.createElement('input')) && (placeholder=obj.getAttribute('placeholder'))){//判断是否是iE,并且对象存在,并把对象的placeholder的返回值赋值给placeholder
var idLabel=obj.id;
if(!idLabel){//判断是否有id
idLabel='placeholder_'+new Date().getTime();
obj.id=idLabel;
}
var ieLabel=document.createElement('label');//创建label标签
ieLabel.htmlFor=idLabel;
with(ieLabel.style){
position='absolute';
left='4px';
top='14px';
fontSize='12px';
color='#a9a9a9';
};
obj.parentNode.insertBefore(ieLabel,obj);//对象的父节点后的子节点前面添加
obj.onfocus=function(){
ieLabel.innerHTML='';
};
obj.onblur=function(){
if(this.value===''){
ieLabel.innerHTML=placeholder;
};
};
if(obj.value===''){//样式的初始化
ieLabel.innerHTML=placeholder;
};
};
};
ieInput(document.getElementById('userName'));
ieInput(document.getElementById('password'));

浙公网安备 33010602011771号