有時候我們需要在登陸表單有一些提示言,比如“請輸入使用者名稱”和“請輸入密碼”等語言,至於使用者名稱好說,但是在密碼框中出現“請輸入密碼”這樣的語言就有點麻煩了,因為在密碼框輸入的內容不會以明碼顯示。如果動態控制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"密碼框顯示,原來顯示的文字框隱藏,也就是說做了一個替換而已。
以上內容是小編給大家分享的JavaScript如何?在密碼框中出現提示的相關知識,希望大家喜歡。