<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>placeholder</title> <style type="text/css"> .label{position: relative; display: inline-block; *zoom:1; *display: inline; *vertical-align: middle;} .label label{ position: absolute; left:0px; top:0; font-size: 12px;cursor: text; text-indent: 5px;} .label input{ padding: 9px 5px; height: 14px; line-height: normal; border: 1px solid #ccc; font-size: 14px;} </style> </head> <body> 请输入用户名: <div class="label"> <label for="user">请输入用户名</label> <input type="text" id="user" /> </div> </body> </html> <script type="text/javascript"> var aLabel=document.getElementsByTagName("label")[0]; var aInput=document.getElementsByTagName("input")[0]; aLabel.style.lineHeight=aLabel.style.height=aInput.offsetHeight+"px"; if (aInput.value.length!=0){ aLabel.style.display="none" }else{ aLabel.style.display="block" }; aInput.onfocus=function(){ aLabel.style.display="none"; } aInput.onblur=function(){ if (aInput.value.length!=0){ aLabel.style.display="none" }else{ aLabel.style.display="block"; }; } </script>
方法二
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>placeholder</title> </head> <body> <input type="text" placeholder="请输入用户名" /> </body> </html> <script> function placeholder(opts){ if("placeholder" in document.createElement(‘input‘)){ return; }else{ this.obj=opts.obj; this.init(); this.focus(); this.blur(); } } placeholder.prototype.init= function(){ if (this.obj.getAttribute("placeholder") && this.obj.value.length==0){ this.obj.value=this.obj.getAttribute("placeholder"); } }; placeholder.prototype.focus=function(){ var _this=this; this.obj.onfocus=function(){ if (_this.obj.value==_this.obj.getAttribute("placeholder")){ _this.obj.value=""; }; } }; placeholder.prototype.blur=function(){ var _this=this; this.obj.onblur=function(){ if (_this.obj.value.length==0){ _this.obj.value=_this.obj.getAttribute("placeholder"); }; } }; var aInput=document.getElementsByTagName("input")[0]; new placeholder({"obj":aInput}); </script>
方法三,
背景图片,限制太多,代码就不贴上来了
时间: 2024-10-01 00:29:08