在登入或設定新密碼時,因為遮罩星號(●●●●)導致打錯字是常見的問題。提供一個「顯示/隱藏密碼」的按鈕,能讓使用者隨時確認輸入內容,不再那麼容易因為不確定自己輸入了甚麼導致被鎖住。
getAttribute('type') 與 setAttribute('type', 'text'):讀取並動態變更 <input> 的 type 屬性值,直接利用瀏覽器原生機制進行密碼與明碼的即時轉換。aria-label 標籤,做到視覺反饋與無障礙網頁體驗。1. 動態切換 input.type 屬性
為什麼選用這個方法?
瀏覽器的 <input type="password"> 原生就會將輸入內容遮罩成點點(●●●●)。要讓使用者確認輸入的密碼是否正確,最快的方法就是直接透過 JavaScript 將其 type 屬性在 "password" 與 "text" 之間進行切換。
這個機制在幹嘛?
password:輸入內容會被隱藏(顯示為黑點/星號)。text:輸入內容會以明碼形式完整呈現。2. 狀態同步與 Accessibility (無障礙設計)
為什麼需要同步更新圖示與屬性?
切換 type 的同時,我們必須同步更新切換按鈕的圖示以及 aria-label 屬性,這樣不僅能給一般使用者明確的視覺反饋,也能讓使用螢幕閱讀器的視覺障礙使用者清楚知道目前的輸入狀態。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>第十五課 - 密碼顯示與隱藏切換</title>
<style>
body { font-family: sans-serif; padding: 40px; background-color: #f8f9fa; }
.form-card { max-width: 400px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.08); }
label { font-weight: bold; color: #333; display: block; margin-bottom: 8px; }
/* 輸入框與按鈕的定位容器 */
.password-wrapper {
position: relative;
display: flex;
align-items: center;
}
/* 密碼輸入框 */
.password-wrapper input {
width: 100%;
padding: 12px 45px 12px 12px; /* 右側留出位置給切換按鈕 */
font-size: 16px;
border: 2px solid #ced4da;
border-radius: 6px;
outline: none;
box-sizing: border-box;
transition: border-color 0.2s ease;
}
.password-wrapper input:focus {
border-color: #007bff;
}
/* 顯示/隱藏切換按鈕 */
.toggle-btn {
position: absolute;
right: 10px;
background: none;
border: none;
font-size: 18px;
cursor: pointer;
padding: 5px;
color: #6c757d;
user-select: none; /* 防止連點時選取到文字 */
}
.toggle-btn:hover {
color: #333;
}
</style>
</head>
<body>
<div class="form-card">
<label for="passwordInput">請輸入帳戶密碼</label>
<div class="password-wrapper">
<input type="password" id="passwordInput" placeholder="請輸入密碼...">
<button type="button" id="togglePasswordBtn" class="toggle-btn" aria-label="顯示密碼">👁️</button>
</div>
</div>
<script>
// ----------------------------------------------------
// JavaScript 邏輯 (type 屬性切換與圖示更新)
// ----------------------------------------------------
// 第一步:取得輸入框 DOM 與切換按鈕 DOM
const passwordInput = document.getElementById("passwordInput");
const togglePasswordBtn = document.getElementById("togglePasswordBtn");
// 第二步:為切換按鈕綁定點擊事件
togglePasswordBtn.addEventListener("click", function() {
// 1. 檢查當前 input 的 type 屬性
const currentType = passwordInput.getAttribute("type");
// 2. 進行三元運算條件切換
if (currentType === "password") {
// 從密碼切換為明碼
passwordInput.setAttribute("type", "text");
togglePasswordBtn.innerText = "X"; // X為遮眼圖示
togglePasswordBtn.setAttribute("aria-label", "隱藏密碼");
} else {
// 從明碼切換回密碼
passwordInput.setAttribute("type", "password");
togglePasswordBtn.innerText = "O"; // O為睜眼圖示
togglePasswordBtn.setAttribute("aria-label", "顯示密碼");
}
});
</script>
</body>
</html>
今天我們學會了如何操作 <input> 原生屬性來優化使用者表單體驗。這個密碼切換是所有登入頁、註冊頁與修改密碼頁面的必備功能。
使用者填完表單後,在按下送出時,該如何用 JavaScript 進行「格式驗證(Validation)」與錯誤提示呢?
【第十六課】表單與驗證:即時表單驗證與錯誤提示(RegExp 正則表達式與 submit 事件),我們將學習如何進行電子郵件與密碼格式的安全過濾。