JavaScript实现输入框(密码框)出现提示语

有时候我们需要在登陆表单有一些提示语言,比如“请输入用户名”和“请输入密码”等语言,至于用户名好说,但是在密码框中出现“请输入密码”这样的语言就有点麻烦了,因为在密码框输入的内容不会以明码显示。如果动态的控制type属性的话就有兼容性问题,如果input已经存在于页面中的话,在IE8和IE8以下浏览器中,type属性是只读的。所以就得想其他办法,代码如下:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta content="https://www.jb51.net/" /> <title>脚本之家</title> <style type="text/css"> #tx{ width:100px; } #pwd{ display:none; width:100px; } </style> <script type="text/javascript"> window.onload=function(){ var tx=document.getElementById("tx"); var pwd=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> <input type="text" value="密码"/> <input type="password" /> </body> </html>

以上代码实现了我们的要求,可以出现明码的提示,当输入密码的时候就是以密码方式输入。

实现的原理非常的简单,在默认状态以type="text"文本框显示,当点击文本框的时候,以type="password"密码框显示,原来显示的文本框隐藏,也就是说做了一个替换而已。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwjdw.html