萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現密碼輸入框明文/密文切換顯示

需求場景

登入表單中,使用者希望檢視剛輸入的密碼是否正確,提供「顯示密碼」勾選框或按鈕切換 type="password" ↔ type="text"。

原生 JS 實作(現代寫法)


<label>
  <input type="password" id="pwd" value="523654" />
  <button type="button" id="toggleBtn">顯示密碼</button>
</label>

<script>
const input = document.getElementById('pwd');
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', () => {
  const isPwd = input.type === 'password';
  input.type = isPwd ? 'text' : 'password';
  btn.textContent = isPwd ? '隱藏密碼' : '顯示密碼';
});
</script>

jQuery 版(舊專案相容)


$('#toggleBtn').click(function() {
  var $pwd = $('#pwd');
  if ($pwd.attr('type') === 'password') {
    $pwd.attr('type', 'text');
    $(this).text('隱藏密碼');
  } else {
    $pwd.attr('type', 'password');
    $(this).text('顯示密碼');
  }
});

注意:IE9 以下不支援動態修改 type 屬性,需採用「建立新 input 替換」或「雙 input 切換顯示」方案。

IE 相容方案:雙 Input 切換


<span id="pwdWrap">
  <input type="password" id="pwd1" value="523654" />
  <input type="text" id="pwd2" value="523654" style="display:none" />
</span>
<button id="toggleBtn">顯示密碼</button>

<script>
$('#toggleBtn').click(function() {
  var $p1 = $('#pwd1'), $p2 = $('#pwd2');
  if ($p1.is(':visible')) {
    $p2.val($p1.val()).show(); $p1.hide();
    $(this).text('隱藏密碼');
  } else {
    $p1.val($p2.val()).show(); $p2.hide();
    $(this).text('顯示密碼');
  }
});
</script>

安全性與 UX 建議

  • 預設為隱藏(type="password"),避免肩窺洩露。
  • 切換時保持輸入焦點:input.focus()。
  • 加入 autocomplete="current-password" 協助瀏覽器自動填充。
  • 敏感場景(銀行、後台)建議**不提供**顯示功能,或加入「顯示 3 秒自動隱藏」計時器。
copyright © 萬盛學電腦網 all rights reserved