asp.net鼠标点击TextBox控件后清空值
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript" language="javascript"> //得到焦点时触发事件 function onFocusFun(element, elementValue) { if (element.value == elementValue) { element.value = ""; element.style.color = ""; } } //离开输入框时触发事件 function onblurFun(element, elementValue) { if (element.value == '') { element.style.color = "#808080"; element.value = elementValue; } } </script> </head> <body> <form id="form1" runat="server"> <div> c#鼠标点击TextBox控件后清空值 <table cellpadding="0" cellspacing="0" width="280"> <tr> <td colspan="2"> 方法一:通过javascript </td> </tr> <tr> <td> 用户名: </td> <td> <asp:TextBox ID="txt_User" runat="server" Text="请输入用户名" ForeColor="#808080" OnFocus="onFocusFun(this,'请输入用户名')" OnBlur="onblurFun(this,'请输入用户名')"></asp:TextBox> </td> </tr> <tr> <td> 密码: </td> <td> <asp:TextBox ID="txt_pwd" runat="server"></asp:TextBox> </td> </tr> </table> <br /> <table width="280"> <tr> <td colspan="2"> 方法二:通过后台调用实现 </td> </tr> <tr> <td> 用户名 </td> <td> <asp:TextBox ID="txtName" runat="server" Text="请输入用户名" ForeColor="#808080" OnFocus="onFocusFun(this,'请输入用户名')" OnBlur="onblurFun(this,'请输入用户名')"></asp:TextBox> </td> </tr> </table> </div> </form> </body> </html>
protected void Page_Load(object sender, EventArgs e) { txtName.Attributes.Add("Value", "请输入用户名"); txtName.Attributes.Add("OnFocus", "if(this.value=='请输入用户名') {this.value=''}"); txtName.Attributes.Add("OnBlur", "if(this.value==''){this.value='请输入用户名'}"); if (!IsPostBack) { } }