有時候我們需要在登陸表單有一些提示語言,比如“請輸入用戶名”和“請輸入密碼”等語言,至於用戶名好說,但是在密碼框中出現“請輸入密碼”這樣的語言就有點麻煩了,因為在密碼框輸入的內容不會以明碼顯示。如果動態的控制type屬性的話就有兼容性問題,如果input已經存在於頁面中的話,在IE8和IE8以下浏覽器中,type屬性是只讀的。所以就得想其他辦法,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://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="密碼" id="tx"/>
<input type="password" id="pwd" />
</body>
</html>
以上代碼實現了我們的要求,可以出現明碼的提示,當輸入密碼的時候就是以密碼方式輸入。
實現的原理非常的簡單,在默認狀態以type="text"文本框顯示,當點擊文本框的時候,以type="password"密碼框顯示,原來顯示的文本框隱藏,也就是說做了一個替換而已。