如何实现在密码框如出现提示语

如何实现在密码框如出现提示语:
有时候我们需要在登陆表单有一些提示语言,比如“请输入用户民”和“请输入密码”等语言,至于用户名好说,但是在 密码框中出现“请输入密码”这样的语言就有点麻烦了,因为在密码框输入的内容不会以明码显示。如果动态的控制type属性的话就有兼容性问题,如果 input已经存在于页面中的话,在IE8和IE8以下浏览器中,type属性是只读的。所以就得想其他办法,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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="密码" id="tx"/>
<input type="password" id="pwd" />
</body>

</html>

以上代码实现了我们的要求,可以出现明码的提示,当输入密码的时候就是以密码方式输入。
实现的原理非常的简单,在默认状态以type="text"文本框显示,当点击文本框的时候,以type="password"密码框显示,原来显示的文本框隐藏,也就是说做了一个替换而已。

第二种方法:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>input输入提示</title>
<style>
ul{ list-style:none;}
.gray{ border:2px solid gray;}
</style>
</head>
 
<body>
<ul>
    <li>姓名:<input type="text" id="username" value="请输入姓名" style="color:#CCC;"/></li>
    <li>密码:<input type="password" id="pw"/></li>
</ul>
<script type="text/javascript">
var username=document.getElementById("username");
var pw=document.getElementById("pw");
 
username.onfocus=function(){//onfocus 获得焦点
    this.className="gray";
    this.value="";
}
username.onblur=function(){//onblur 失去焦点
    this.className="";
    this.value="请输入姓名";
}
pw.onfocus=function(){
    this.className="gray";
    this.value="";
}
pw.onblur=function(){
    this.className="";
    this.style.type="text";
    this.value="请输入密码";
     
}
</script>
</body>
</html>
 

posted on 2015-12-31 09:21  土dou  阅读(597)  评论(0编辑  收藏  举报