html5原生支持placeholder,对于不支持的浏览器(ie),可用js模拟实现。
js代码
复制代码 代码如下:
(function(){
//判断是否支持placeholder
function isplaceholer(){
var input = document.createelement('input');
return placeholder in input;
}
//不支持的代码
if(!isplaceholer()){
//创建一个类
function placeholder(obj){
this.input = obj;
this.label = document.createelement('label');
this.label.innerhtml = obj.getattribute('placeholder');
this.label.style.csstext = 'position:absolute; text-indent:4px;color:#999999; font-size:12px;';
if(obj.value != ''){
this.label.style.display = 'none';
}
this.init();
}
placeholder.prototype = {
//取位置
getxy : function(obj){
var left, top;
if(document.documentelement.getboundingclientrect){
var html = document.documentelement,
body = document.body,
pos = obj.getboundingclientrect(),
st = html.scrolltop || body.scrolltop,
sl = html.scrollleft || body.scrollleft,
ct = html.clienttop || body.clienttop,
cl = html.clientleft || body.clientleft;
left = pos.left + sl - cl;
top = pos.top + st - ct;
}
else{
while(obj){
left += obj.offsetleft;
top += obj.offsettop;
obj = obj.offsetparent;
}
}
return{
left: left,
top : top
}
},
//取宽高
getwh : function(obj){
return {
w : obj.offsetwidth,
h : obj.offsetheight
}
},
//添加宽高值方法
setstyles : function(obj,styles){
for(var p in styles){
obj.style[p] = styles[p]+'px';
}
},
init : function(){
var label = this.label,
input = this.input,
xy = this.getxy(input),
wh = this.getwh(input);
this.setstyles(label, {'width':wh.w, 'height':wh.h, 'lineheight':20, 'left':xy.left, 'top':xy.top});
document.body.appendchild(label);
label.onclick = function(){
this.style.display = none;
input.focus();
}
input.onfocus = function(){
label.style.display = none;
};
input.onblur = function(){
if(this.value == ){
label.style.display = block;
}
};
}
}
var inpcoll = document.getelementsbytagname('input'),
textcoll = document.getelementsbytagname('textarea');
//html集合转化为数组
function toarray(coll){
for(var i = 0, a = [], len = coll.length; i a[i] = coll[i];
}
return a;
}
var inparr = toarray(inpcoll),
textarr = toarray(textcoll),
placeholderarr = inparr.concat(textarr);
for (var i = 0; i if (placeholderarr[i].getattribute('placeholder')){
new placeholder(placeholderarr[i]);
}
}
}
})()
html代码:
复制代码 代码如下:
css代码:
复制代码 代码如下:
div,input,textarea{ margin:0; padding:0;}
div{width:400px; margin:100px auto 0;}
input,textarea{width:200px;height:20px; margin-top:5px;line-height:20px;border:1px #666666 solid; background-color:#fff; padding-left:2px;}
textarea{ height:60px; font-size:12px; resize:none;}