<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <style> input{ color: #999; } </style> <body> <input type="text" value="手机" /> <script> /* * 当鼠标点击文本框时,里面的默认文字会隐藏,当鼠标离开文本框时,里面的文字显示。 * 案例分析: * (1)首先表单需要2个事件:获得焦点onfocus,失去焦点onblur * (2)如果获得焦点,判断表单里面内容是否为默认文字,如果是,就清空表单内容 * (3)如果失去焦点,判断表单内容是否为空,如果为空,就将表单内容还原为默认文字 */ //获取事件源 var text=document.querySelector("input"); //注册事件,获得焦点事件 onfocus text.onfocus=function(){ if(text.value=="手机"){ text.value=" "; } text.style.color="#333";//获得焦点需要把输入的文字颜色加深 } //注册事件,失去焦点事件 onblur text.onblur=function(){ if(text.value==" "){ text.value="手机"; } text.style.color="#999";//失去焦点,需要把文本框里面的文字颜色变浅 } </script> </body></html>