首頁 >web前端 >js教程 >js模仿html5 placeholder適應不支援的瀏覽器_javascript技巧

js模仿html5 placeholder適應不支援的瀏覽器_javascript技巧

WBOY
WBOY原創
2016-05-16 17:43:54991瀏覽

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||scrollT Top||
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 : 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;line-height:20px;border:1px #666666 solid; background-color:fffff; -left:2px;} textarea{ height:60px; font-size:12px; resize:none;}
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn