<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS点击输入框让默认文字消失代码</title>
<script type="text/javascript">
//得到焦点时触发事件
function OnFocusFun(element,elementvalue)
{
if(element.value==elementvalue)
{
element.value="";
element.style.color="#000";
}
}
//离开输入框时触发事件
function OnBlurFun(element,elementvalue)
{
if(element.value==""||element.value.replace(/\s/g,"")=="")
{
element.value=elementvalue;
element.style.color="#999";
}
}
</script>
</head>
<body>
<div>
<span>账号:</span>
<input type="text" value="请输入用户名" id="UserId" onfocus="OnFocusFun(this,'请输入用户名')" style="color:#999" onblur="OnBlurFun(this,'请输入用户名')"/>
</div>
<div>
<span>密码:</span>
<input type="text" value="请输入密码" id="Password" onfocus="OnFocusFun(this,'请输入密码')" onblur="OnBlurFun(this,'请输入密码')" style="color:#999" />
</div>
</body>
</html>
网络上有很多相关的文章,我大致搜索了下发现很多都是判断不完善的,特别是对于空格的问题,
有时人们可能一不小心没有输入文字,但是却敲了下空格的情况。以上的代码,其中用正则对空格问题也做了判断。