首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

HTML/JS 實現密碼框明文/密文切換:點擊圖標切換 input type

     編輯:程式設計綜合問答

需求:密碼輸入框旁放一圖標,點擊切換顯示/隱藏密碼。

核心邏輯

<input type="password" id="pwd">
<img src="eye.png" id="toggle" onclick="togglePwd()">

<script>
function togglePwd() {
    var input = document.getElementById('pwd');
    var img = document.getElementById('toggle');
    if (input.type === 'password') {
        input.type = 'text';
        img.src = 'eye-open.png';
    } else {
        input.type = 'password';
        img.src = 'eye.png';
    }
}
</script>

注意事項

  • IE11- 不支持動態修改 type,需替換整個 input 元素或用 <input type="text"> + CSS -webkit-text-security: disc 方案。
  • 移動端建議用 touchstart 事件防點擊穿透。
  • 無障礙:添加 aria-label="顯示/隱藏密碼"。

現代寫法

const toggle = document.getElementById('toggle');
const pwd = document.getElementById('pwd');
toggle.addEventListener('click', () => {
    const show = pwd.type === 'password';
    pwd.type = show ? 'text' : 'password';
    toggle.src = show ? 'eye-open.png' : 'eye.png';
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved