国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js模仿html5 placeholder適應(yīng)于不支持的瀏覽器

2024-05-06 14:20:03
字體:
供稿:網(wǎng)友
html5原生支持placeholder,對于不支持的瀏覽器(ie),可用js模擬實(shí)現(xiàn)。
js代碼
代碼如下:
(function(){
//判斷是否支持placeholder
function isPlaceholer(){
var input = document.createElement('input');
return "placeholder" in input;
}
//不支持的代碼
if(!isPlaceholer()){
//創(chuàng)建一個(gè)類
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集合轉(zhuǎn)化為數(shù)組
function toArray(coll){
for(var i = 0, a = [], len = coll.length; i < len; i++){
a[i] = coll[i];
}
return a;
}
var inpArr = toArray(inpColl),
textArr = toArray(textColl),
placeholderArr = inpArr.concat(textArr);
for (var i = 0; i < placeholderArr.length; i++){
if (placeholderArr[i].getAttribute('placeholder')){
new Placeholder(placeholderArr[i]);
}
}
}
})()

html代碼:
代碼如下:
<div>
<input type="text" placeholder="提示1" /><br>
<textarea placeholder="提示2" /></textarea><br>
<input type="text" placeholder="提示3" /><br>
</div>

css代碼:
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 海原县| 望都县| 高唐县| 德钦县| 霸州市| 镇赉县| 曲麻莱县| 屏东市| 保山市| 昌图县| 札达县| 碌曲县| 安乡县| 安西县| 南昌市| 中江县| 堆龙德庆县| 岐山县| 三台县| 鹤壁市| 宜都市| 奉新县| 阿巴嘎旗| 陈巴尔虎旗| 柘荣县| 邵阳县| 茶陵县| 府谷县| 富平县| 河东区| 景宁| 宜宾市| 朝阳市| 诸城市| 肇庆市| 金沙县| 新邵县| 准格尔旗| 措美县| 新丰县| 连江县|