SoFunction
Updated on 2025-04-07

js imitation html5 placeholder adapts to unsupported browsers


(function(){
//Judge whether placeholder is supported
function isPlaceholer(){
var input = ('input');
return "placeholder" in input;
}
//Unsupported code
if(!isPlaceholer()){
//Create a class
function Placeholder(obj){
= obj;
= ('label');
= ('placeholder');
= 'position:absolute; text-indent:4px;color:#999999; font-size:12px;';
if( != ''){
= 'none';
}
();
}
= {
//Pick the position
getxy : function(obj){
var left, top;
if(){
var html = ,
body = ,
pos = (),
st = || ,
sl = || ,
ct = || ,
cl = || ;
left = + sl - cl;
top = + st - ct;
}
else{
while(obj){
left += ;
top += ;
obj = ;
}
}
return{
left: left,
top : top
}
},
//Take width and height
getwh : function(obj){
return {
w : ,
h :
}
},
//Add a width and height value method
setStyles : function(obj,styles){
for(var p in styles){
[p] = styles[p]+'px';
}
},
init : function(){
var label = ,
input = ,
xy = (input),
wh = (input);
(label, {'width':, 'height':, 'lineHeight':20, 'left':, 'top':});
(label);
= function(){
= "none";
();
}
= function(){
= "none";
};
= function(){
if( == ""){
= "block";
}
};
}
}
var inpColl = ('input'),
textColl = ('textarea');
//Convert html collection into array
function toArray(coll){
for(var i = 0, a = [], len = ; i < len; i++){
a[i] = coll[i];
}
return a;
}
var inpArr = toArray(inpColl),
textArr = toArray(textColl),
placeholderArr = (textArr);
for (var i = 0; i < ; i++){
if (placeholderArr[i].getAttribute('placeholder')){
new Placeholder(placeholderArr[i]);
}
}
}
})()