JavaScript实现输入框(密码框)出现提示语
有时候我们需要在登陆表单有一些提示语言,比如“请输入用户名”和“请输入密码”等语言,至于用户名好说,但是在密码框中出现“请输入密码”这样的语言就有点麻烦了,因为在密码框输入的内容不会以明码显示。如果动态的控制type属性的话就有兼容性问题,如果input已经存在于页面中的话,在IE8和IE8以下浏览器中,type属性是只读的。所以就得想其他办法,代码如下:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<metaname="author"content="https://www.nhooo.com/"/>
<title>毛票票</title>
<styletype="text/css">
#tx{
width:100px;
}
#pwd{
display:none;
width:100px;
}
</style>
<scripttype="text/javascript">
window.onload=function(){
vartx=document.getElementById("tx");
varpwd=document.getElementById("pwd");
tx.onfocus=function(){
if(this.value!="密码")
return;
this.style.display="none";
pwd.style.display="block";
pwd.value="";
pwd.focus();
}
pwd.onblur=function(){
if(this.value!=""){
return;
}
this.style.display="none";
tx.style.display="";
tx.value="密码";
}
}
</script>
</head>
<body>
<inputtype="text"value="密码"id="tx"/>
<inputtype="password"id="pwd"/>
</body>
</html>
以上代码实现了我们的要求,可以出现明码的提示,当输入密码的时候就是以密码方式输入。
实现的原理非常的简单,在默认状态以type="text"文本框显示,当点击文本框的时候,以type="password"密码框显示,原来显示的文本框隐藏,也就是说做了一个替换而已。