很多網站的輸入框預設會帶一段提示文字,滑鼠點進去時自動清空,使用者若什麼都沒填就離開,提示文字又自動回來。本文示範這個常見互動的實作方式。
先補兩個基礎知識。
1、onclick 事件
點擊物件時觸發,主流瀏覽器(IE、Firefox、Opera、Chrome、Safari)都支援。
<html> <head> <meta charset="gb2312"/> <title></title> <style type="text/css"> div{ width:100px; height:100px; background-color:red; } </style> <script type="text/javascript"> window.onload=function(){ var mydiv=document.getElementById("mydiv"); mydiv.onclick=function(){ mydiv.style.backgroundColor="green"; } } </script> </head> <body> <div id="mydiv"></div> </body> </html>
上面為 div 註冊 onclick 處理函數,點擊後背景變綠。
2、onblur 事件
物件失去焦點時觸發。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <style type="text/css"> .mytest{ background-color:green; } </style> <script type="text/javascript"> window.onload=function(){ var username=document.getElementById("username"); username.focus(); username.onblur=function(){ username.style.backgroundColor="green"; } } </script> </head> <body> <input type="text" name="username" id="username" /> </body> </html>
把 onclick 與 onblur 組合起來,就能做出「點擊清空、離開還原」的效果:
<html> <head> <meta charset="gb2312"> <title>點擊文本框清除默認值</title> <script type="text/javascript"> window.onload=function() { var username=document.getElementById("username"); username.onclick=function() { if(username.value=="請輸入您的姓名") { username.value=""; this.focus(); } } username.onblur=function() { if(username.value=="") { username.value="請輸入您的姓名"; } } } </script> </head> <body> <input type="text" value="請輸入您的姓名" id="username" /> </body> </html>
onclick 裡先比對值是否仍是預設提示,是的話才清空;onblur 裡則判斷是否為空,是的話才把提示寫回去。兩個 if 缺一不可,少了前一個會把使用者輸入的內容誤刪,少了後一個則會在輸入一半時把文字蓋掉。
如果換成密碼框,做法要調整一下,因為密碼框不顯示明文,直接寫提示會變成圓點。這部分可以參考「密碼框提示文字」的雙 input 互換方案:預設用 type="text" 顯示提示,取得焦點時換成 type="password" 並清空內容,失去焦點且為空時再換回來。