javascript兼容placeholder代码

<html>
<head>
<meta charset="UTF-8"/>
<title>验证Valid ----placeholder</title>

<style>
span.emptyhint {color:#999;position:absolute;padding:3px;}
</style>
</head>
<body>
<div id=doc3>
<div id="bd" >
<div>
<ul>
<li>
<label>订单主人:</label>
<input type="text" placeholder="请填写订单主人" value="JK">
</li>
<li>
<label>订单号:</label>
<input type="text" placeholder="请填写订单号">
</li>
<li>
<label>备注:</label>
<textarea type="text" placeholder="请填写备注"></textarea>
</li>
</ul>
</div>
</div>
</div>
</body>

<script>

function initPlaceHolders(){
if('placeholder' in document.createElement('input')){ //如果浏览器原生支持placeholder
return ;
}
function target (e){
var e=e||window.event;
return e.target||e.srcElement;
};
function _getEmptyHintEl(el){
var hintEl=el.hintEl;
return hintEl && g(hintEl);
};
function blurFn(e){
var el=target(e);
if(!el || el.tagName !='INPUT' && el.tagName !='TEXTAREA') return;//IE下,onfocusin会在div等元素触发
var emptyHintEl=el.__emptyHintEl;
if(emptyHintEl){
//clearTimeout(el.__placeholderTimer||0);
//el.__placeholderTimer=setTimeout(function(){//在360浏览器下,autocomplete会先blur再change
if(el.value) emptyHintEl.style.display='none';
else emptyHintEl.style.display='';
//},600);
}
};
function focusFn(e){
var el=target(e);
if(!el || el.tagName !='INPUT' && el.tagName !='TEXTAREA') return;//IE下,onfocusin会在div等元素触发
var emptyHintEl=el.__emptyHintEl;
if(emptyHintEl){
//clearTimeout(el.__placeholderTimer||0);
emptyHintEl.style.display='none';
}
};
if(document.addEventListener){//ie
document.addEventListener('focus',focusFn, true);
document.addEventListener('blur', blurFn, true);
}
else{
document.attachEvent('onfocusin',focusFn);
document.attachEvent('onfocusout',blurFn);
}

var elss=[document.getElementsByTagName('input'),document.getElementsByTagName('textarea')];
for(var n=0;n<2;n++){
var els=elss[n];
for(var i =0;i<els.length;i++){
var el=els[i];
var placeholder=el.getAttribute('placeholder'),
emptyHintEl=el.__emptyHintEl;
if(placeholder && !emptyHintEl){
emptyHintEl=document.createElement('span');
emptyHintEl.innerHTML=placeholder;
emptyHintEl.className='emptyhint';
emptyHintEl.onclick=function (el){return function(){try{el.focus();}catch(ex){}}}(el);
if(el.value) emptyHintEl.style.display='none';
el.parentNode.insertBefore(emptyHintEl,el);
el.__emptyHintEl=emptyHintEl;
}
}
}
}

initPlaceHolders();

</script>
</html>

来源:http://www.cnblogs.com/jkisjk/archive/2011/02/23/placdeholder_solo.html,感谢作者

原创文章:javascript兼容placeholder代码 ,未经许可,禁止转载,©版权所有
原文出处:前端开发博客 (http://caibaojian.com/javascript-placehoder-hack.html)

“javascript兼容placeholder代码”有1个评论

  1. 扬-帆-远-航

    这个似乎不能解决password问题吧?可以参考下这个帖子,我刚刚用了可以兼容Chrome、Firefox、Safari、IE8~11,不过他的js代码稍微复杂点,<a href="http://www.weidublog.com/index.php/post/8.html">placeholder主流浏览器兼容性测试和兼容方法</a>

    登录回复