多網站的需要填寫的文本框在默認狀態下都會給出一個默認的提示語言,當鼠標點擊此文本框的時候能夠將里面的默認文本清除,當刪除輸入的文本且焦點離開文本框的時候再將默認的文本寫入文本框。
代碼如下:
<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://m.survivalescaperooms.com/" /><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> 以上代碼實現了我們的要求,當點擊文本框的時候能夠清除文本框中的內容,如果文本框沒有輸入任何內容,這個時候鼠標焦點離開文本框的時候,會將文本框的值恢復到默認狀態。不過如果密碼框肯恩有點麻煩,因為密碼框并非顯示的明文,解決方案可以參閱JavaScript實現輸入框(密碼框)出現提示語一章節。
鼠標離開文本框時觸發js的方法
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="textBox.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript"> function validate() { var name = document.getElementById("txtName"); if (name.value == 2) { alert("你必須不是二!"); name.focus(); return false; } return true; } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtName" onblur="validate();" runat="server" /> </div> </form> </body> </html> 新聞熱點
疑難解答