【程式碼筆記】HTML+CSS+JavaScript實現密碼輸入框顯示文字
阿新 • • 發佈:2019-01-24
原理:
通過設定一個input為password,預設display為none,再設定一個input為text設定為block,利用js指令碼控制顯隱。
具體思路:
給type型別為text的輸入框加一個點選事件,點選事件是設定text型別輸入框的display為none,設定password型別輸入框為block,並獲取焦點。
給type型別為password的輸入框加一個失去焦點事件,失去焦點事件是先判斷password是否為空。如果為空,就設定text型別輸入框的display為block,設定password型別輸入框為none;如果不為空,就結束方法。
具體實現程式碼:
JS檔案:
function changePwd(obj) { obj.style.display = "none"; if (obj.type == "text") { document.getElementById('pwdtext').style.display = "block"; document.getElementById('pwdtext').focus(); } else { if (obj.value == "") document.getElementById('pwdshow').style.display = "block"; else { obj.style.display = "block"; } } }
HTML/JSP檔案:
<div class="pwd">
<input type="password" name="pwd" id="pwdtext" onblur="changePwd(this);" />
<span style="white-space:pre"> </span><input type="text" id="pwdshow" value="Password" onfocus="changePwd(this);" />
</div>
CSS檔案:
.pwd { margin-top: 20px; margin-left: 40px; border: 1px solid #dcdcdc; width: 348px; height: 40px; line-height: 40px; } .pwd input { color: #dcdcdc; width: 289px; border: 0; line-height: 40px; float: left; } #pwdtext { outline: none; color: #000000; display: none; }
效果圖: