设置文本输入框默认值

有默认值,有一个灰色文字样式(提示用户的信息);
获得焦点后,清空默认值让用户输入文字,这时失去焦点后,给一个样式名来改变文字颜色,这种情况下再次获得焦点时不清空用户已输入的值。
如果用户没有输入任何值,返回默认值,灰色文本样式

<!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>
    <title>DEMO</title>
    <style type="text/css">
	#form div {
		position: relative;
	}
	#form .tip {
		position: absolute;
		top: 1px;
		left: 3px;
		color: #ccc;
	}
	#form input {
		color: red;
	}
    </style>
</head>
<body>
	<div id="form">
		<div><label class="tip" for="textbox1">LABEL1</label><input id="textbox1" type="text" /></div>
		<div><label class="tip" for="textbox2">LABEL2</label><input id="textbox2" type="text" /></div>

		<div><label class="tip" for="textbox3">LABEL3</label><input id="textbox3" type="text" /></div>
		<div><label class="tip" for="textbox4">LABEL4</label><input id="textbox4" type="text" /></div>
		<div><label class="tip" for="textbox5">LABEL5</label><input id="textbox5" type="text" /></div>
		<div><label class="tip" for="textbox6">LABEL6</label><input id="textbox6" type="text" /></div>
	</div>
	<script type="text/javascript">
		var form1 = document.getElementById("form"),
			isIE = /*@cc_on!@*/0;
		function focusin(event) {			
			var e = isIE? window.event: event,
				target = isIE? e.srcElement: e.target;
			target.previousSibling.style.display = "none";
			target.parentNode.className += " focus";
		}		
		function focusout(event) {
			var e = isIE? window.event: event,
				target = isIE? e.srcElement: e.target;
			if(target.value === "") {
				target.previousSibling.style.display = "inline";
			}
			target.parentNode.className = target.parentNode.className.replace(/\s+focus/, "");		
		}
		if(isIE) {
			form1.onfocusin = focusin;
			form1.onfocusout = focusout;
		} else {
			form1.addEventListener("focus", focusin, true);
			form1.addEventListener("blur", focusout, true);
		}
	</script>

</body>
</html>
posted @ 2011-07-26 17:17  沫鱼  阅读(13122)  评论(0编辑  收藏  举报