前言
在填寫社群貼文、評價回饋或個人簡介時,介面上即時顯示「目前字數 / 上限字數」並在超標時跳出紅色警告,是非常貼心且標準的 UX 設計。今天我們就來學習如何用 input 事件做到零延遲的字數監控。
核心觀念與語法拆解
input 事件:與 change 事件不同,input 事件會在輸入框內容發生任何變動(打字、刪除、貼上)的當下瞬間觸發,是做即時互動的最佳選擇。
狀態邊界條件判斷:計算 value.length 與設定的上限制關係,當 remaining < 0 時動態切換 CSS .warning 樣式,提供即時的視覺警示。
實作程式碼
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>第十四課 - 字數即時統計與限制告警</title>
<style>
body { font-family: sans-serif; padding: 40px; background-color: #f8f9fa; }
.input-card { max-width: 500px; margin: 0 auto; background: white; padding: 25px; 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; }
/* 輸入框基本樣式 */
textarea {
width: 100%;
height: 120px;
padding: 12px;
font-size: 15px;
border: 2px solid #ced4da;
border-radius: 6px;
box-sizing: border-box;
resize: vertical;
transition: border-color 0.2s ease;
outline: none;
}
textarea:focus { border-color: #007bff; }
/* 當字數超過上限時的警示樣式 */
textarea.warning {
border-color: #dc3545;
background-color: #fff8f8;
}
/* 底部分頁資訊 */
.counter-info {
display: flex;
justify-content: space-between;
margin-top: 8px;
font-size: 14px;
color: #6c757d;
}
/* 警告文字色彩 */
.counter-info.warning {
color: #dc3545;
font-weight: bold;
}
</style>
</head>
<body>
<div class="input-card">
<label for="userBio">個人簡介 (限 100 字以內)</label>
<textarea id="userBio" placeholder="請輸入您的個人簡介..."></textarea>
<div id="counterInfo" class="counter-info">
<span id="hintText">還可以輸入 100 字</span>
<span><strong id="charCount">0</strong> / 100</span>
</div>
</div>
<script>
// ----------------------------------------------------
// JavaScript 邏輯 (input 事件與即時字數監控)
// ----------------------------------------------------
// 第一步:取得 DOM 元素與設定最大字數限制
const userBio = document.getElementById("userBio");
const charCount = document.getElementById("charCount");
const hintText = document.getElementById("hintText");
const counterInfo = document.getElementById("counterInfo");
const MAX_LIMIT = 100;
// 第二步:監聽 textarea 的 input 事件 (即時觸發)
userBio.addEventListener("input", function() {
// 1. 取得當前輸入文字長度
const currentLength = userBio.value.length;
const remaining = MAX_LIMIT - currentLength;
// 2. 更新字數顯示 DOM
charCount.innerText = currentLength;
// 3. 判斷字數是否超出限制
if (remaining < 0) {
// 超出限制:加上警告 Class,並更新提示文字
userBio.classList.add("warning");
counterInfo.classList.add("warning");
hintText.innerText = `已超出 ${Math.abs(remaining)} 個字!`;
} else {
// 未超出限制:移除警告 Class,恢復一般提示
userBio.classList.remove("warning");
counterInfo.classList.remove("warning");
hintText.innerText = `還可以輸入 ${remaining} 字`;
}
});
</script>
</body>
</html>
總結與實用情境
今天我們掌握了表單事件處理中最核心的 input 監聽。這套字數監控邏輯可以直接應用在留言板、客服表單、簡訊發送系統等任何需要輸入控制的場景中。
下集預告
在登入或註冊頁面中,密碼輸入框旁邊常常有一個「小眼睛」按鈕,點擊可以切換顯示/隱藏明碼,所以下一集:【第十五課】表單與輸入:密碼顯示/隱藏切換(type 屬性控制與圖示狀態),我們將學習如何靈活切換 input 的 type 屬性。