使用 JavaScript 和 CSS 的文本框水印






4.64/5 (10投票s)
在文本框中应用水印,使用 JavaScript。
引言
在本文中,我将解释如何使用 JavaScript 和 CSS 实现 TextBox 水印,这非常有用,并且与 AJAX 相比,使用的资源更少。
概述
JavaScript 用于实现 TextBox 的 ‘onfocus
’ 和 ‘onblur
’ 事件,CSS 用于装饰 TextBox
。
Using the Code
a.Bind
将 onfocus
事件绑定到移除水印的操作,并将 onblur
事件绑定到将 TextBox 装饰为水印的操作。
<style type="text/css">
.WaterMarkedTextBox
{
height: 16px;
width: 168px;
padding: 2px 2 2 2px;
border: 1px solid #BEBEBE;
background-color: #F0F8FF;
color: gray;
font-size: 8pt;
text-align: center;
}
.WaterMarkedTextBoxPSW
{
background-position: center;
height: 16px;
width: 168px;
padding: 2px 2 2 2px;
border: 1px solid #BEBEBE;
background-color: #F0F8FF;
color: white;
vertical-align: middle;
text-align: right;
background-image: url(Images/psw_wMark.png);
background-repeat: no-repeat;
}
.NormalTextBox
{
height: 16px;
width: 168px;
}
</style>
<script language="javascript" type="text/javascript">
function Focus(objname, waterMarkText) {
obj = document.getElementById(objname);
if (obj.value == waterMarkText) {
obj.value = "";
obj.className = "NormalTextBox";
if (obj.value == "User ID" || obj.value == "" || obj.value == null) {
obj.style.color = "black";
}
}
}
function Blur(objname, waterMarkText) {
obj = document.getElementById(objname);
if (obj.value == "") {
obj.value = waterMarkText;
if (objname != "txtPwd") {
obj.className = "WaterMarkedTextBox";
}
else {
obj.className = "WaterMarkedTextBoxPSW";
}
}
else {
obj.className = "NormalTextBox";
}
if (obj.value == "User ID" || obj.value == "" || obj.value == null) {
obj.style.color = "gray";
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<h3>
Watermark Textbox using JavaScript and CSS</h3>
</div>
<table>
<tr>
<td>
User Id
</td>
<td>
<asp:TextBox ID="txtUserId" runat="server"
onfocus="Focus(this.id,'User ID')"
onblur="Blur(this.id,'User ID')"
Width="126px" CssClass="WaterMarkedTextBox">User ID</asp:TextBox>
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPwd" TextMode="Password"
runat="server" onfocus="Focus(this.id,'')"
onblur="Blur(this.id,'')" Width="126px"
CssClass="WaterMarkedTextBoxPSW" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</td>
</tr>
</table>
</form>
</body>
历史
- 2009年5月29日:初始发布