下面是个输入框
当没有获取焦点时,显示灰色的提示信息:
当用户输入时,隐藏提示文字,且恢复为默认色:
当输入框失去焦点,如果输入为空,需还原提示信息:
要求: a) 写出HTML和CSS代码 b) 用JavaScript实现功能
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> input{ border: solid 1px silver; width: 120px; } </style> </head> <body> <input type="text" id="hello" placeholder="请输入内容" value=""> <script> function addEvent(el,type,listener){ if(el.addEventListener){ el.addEventListener(type,listener,false); }else if(el.attachEvent){ el.attachEvent("on"+type,listener); }else{ el["on"+type]=listener; } } var input=document.getElementById("hello"); function getTar(e){ var event=e||window.event; return event.target||event.srcElement; } function focusHandler(e){ var target=getTar(e); target.placeholder=""; } function blurHandler(e){ var target=getTar(e); if(this.value!=""){ this.value=target.value; }else{ target.placeholder="请输入内容"; } } addEvent(input,"focus",focusHandler); addEvent(input,"blur",blurHandler); </script> </body> </html>
CSS:#input{border: 1px solid #ccc;} HTML:<input type="text" id="input" value="请输入内容"> JS: window.onload=function(){ var oInput=document.getElementById("input"); var value=oInput.value; oInput.onfocus=function(){ this.value=""; }; oInput.onblur=function(){ if (!this.value) { this.value=value; } }; }