在輸入複雜密碼時,使用者常因無法確認自己是否打錯字而感到困擾。現代網站的標準配備「顯示/隱藏密碼」按鈕,其實實現起來非常簡單。今天我們學習如何透過 DOM 直接修改表單屬性。
在登入或註冊頁面中,「點擊眼睛圖示查看密碼」是非常常見的功能。這堂課的核心觀念非常簡單:透過切換 <input> 標籤的 type 屬性(password <—>text),來改變密碼的顯示狀態。
這次我們會用到 1 個核心屬性修改 與 1 個條件判斷式:
input.type 屬性HTML 原生的 <input> 只要將 type 設為 "password",瀏覽器就會自動將輸入內容變成圓點掩碼;設為 "text",就會還原成一般看得見的明文。直接修改這個屬性是改變密碼顯示狀態最快的做法。
它是 <input> 標籤內建的屬性。在 JavaScript 中,我們可以透過 input.type = "text" 來直接讀取或動態變更它的類型。
input.setAttribute('type', 'text')
setAttribute 來修改屬性。input.type 語法更簡潔、執行效率更高,是前端開發者更推薦的寫法。type="text" 的輸入框來替換
if...else 條件判斷(三元運算子 / 條件式)if...else 條件判斷我們需要知道目前輸入框是處於「隱藏(password)」還是「顯示(text)」狀態,才能決定點擊按鈕後要切換成哪一種狀態。
讓程式根據條件(true 或 false)來決定要執行哪一段程式碼。
passwordInput.type = (passwordInput.type === "password") ? "text" : "password"
if...else 精簡成一行寫法。if...else 結構更容易閱讀與維護。請建立一個 day3.html 測試檔:
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>Day 3 - 顯示/隱藏密碼切換器</title>
<style>
body {
font-family: sans-serif;
padding: 40px;
background-color: #f5f5f5;
}
.input-group {
display: flex;
align-items: center;
gap: 10px;
}
/* 輸入框樣式 */
input[type="password"],
input[type="text"] {
padding: 10px 15px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
outline: none;
}
/* 切換按鈕樣式 */
button {
padding: 10px 15px;
font-size: 14px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h2>表單應用:密碼顯示/隱藏切換</h2>
<div class="input-group">
<!-- 密碼輸入框,預設 type 為 "password" -->
<input type="password" id="passwordInput" placeholder="請輸入密碼">
<!-- 切換按鈕 -->
<button id="toggleBtn">顯示密碼</button>
</div>
<script>
// ----------------------------------------------------
// JavaScript 邏輯 (DOM 操作)
// ----------------------------------------------------
// 第一步:透過 document.getElementById 取得密碼輸入框與切換按鈕的控制權
const passwordInput = document.getElementById("passwordInput");
const toggleBtn = document.getElementById("toggleBtn");
// 第二步:使用 addEventListener 為按鈕綁定「點擊 (click)」事件監聽器
toggleBtn.addEventListener("click", function() {
// 第三步:用 if 判斷目前輸入框的 type 屬性是否為 "password"
if (passwordInput.type === "password") {
// 條件成立(目前是隱藏狀態):
// 1. 將 type 修改為 "text",讓密碼變成明文顯示
passwordInput.type = "text";
// 2. 修改按鈕文字,提示使用者點擊後會隱藏密碼
toggleBtn.innerText = "隱藏密碼";
} else {
// 條件不成立(目前是顯示狀態):
// 1. 將 type 改回 "password",重新將密碼遮蔽
passwordInput.type = "password";
// 2. 將按鈕文字還原為提示顯示密碼
toggleBtn.innerText = "顯示密碼";
}
});
</script>
</body>
</html>