在 Twitter (X)、FB 貼文或發送簡訊時,我們常看到「即時字數統計」與「超過上限顯示警告紅字」。這個即時視覺反饋能防止使用者送出無效資料。今天我們就來用 DOM 操作實作這個貼心的介面細節
1. textarea.value.length 屬性
為什麼選用這個屬性?
我們需要「算出一共有幾個字」。DOM 元素的 .value 取得的是輸入框內的字串文字,再接上 JavaScript 原生的 .length 屬性,就可以立刻算出目前輸入了幾個字元(包含空格與換行)。
這個屬性在幹嘛?
textarea.value 取得文字內容,.length 計算字串長度,回傳數字(例如 15)。
有沒有其他替代方案?
textarea.innerText.length
innerText 讀取文字。<input> 或 <textarea> 這類表單元素,裡面的輸入內容必須用 .value 讀取,innerText 在表單輸入框裡面是抓不到值的。2. 動態文字與 CSS 樣式控制 (innerText + classList.add / remove)
為什麼選用這個組合?
我們需要做兩件事:1. 更新畫面上顯示的數字(數字變化);2. 當字數超過限制時讓警告文字「變紅色」(視覺反饋)。
這個組合在幹嘛?
counter.innerText = currentLength + " / " + maxLength 負責修改畫面的計數文字。currentLength > maxLength 時,使用 classList.add('warning') 切換紅字警告。有沒有其他替代方案?
counter.style.color = 'red'
請建立一個 day6.html 測試檔:
HTML
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>第六課 - 字數計數器與上限提示</title>
<style>
body { font-family: sans-serif; padding: 40px; background-color: #f8f9fa; }
.container { width: 350px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
/* 文字輸入框樣式 */
textarea {
width: 100%;
height: 100px;
padding: 10px;
box-sizing: border-box;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
resize: none; /* 限制使用者隨意拉伸框高 */
outline: none;
}
/* 計數器數字樣式 */
.counter-info {
text-align: right;
font-size: 14px;
color: #666;
margin-top: 8px;
}
/* 超過字數限制時的警告樣式 */
.counter-info.warning {
color: #e74c3c; /* 警告紅 */
font-weight: bold;
}
/* 輸入框超過字數時的外框紅邊 */
textarea.warning-border {
border-color: #e74c3c;
}</style>
</head>
<body>
<div class="container">
<h3>社群貼文輸入框</h3>
<!-- 設定限制為 50 個字 -->
<textarea id="tweetInput" placeholder="在想些什麼?(最多 50 字)"></textarea>
<div id="counter" class="counter-info">0 / 50</div>
</div>
<script>
// ----------------------------------------------------
// JavaScript 邏輯 (DOM 操作)
// ----------------------------------------------------
// 第一步:取得多行輸入框 (textarea) 與字數提示區域 (div) 的 DOM 控制權
const tweetInput = document.getElementById("tweetInput");
const counter = document.getElementById("counter");
// 設定最大字數上限上限
const maxLength = 50;
// 第二步:為輸入框綁定 'input' 事件,打字、貼上、刪除都會即時觸發
tweetInput.addEventListener("input", function(){
// 第三步:讀取輸入框當前的文字長度 (.length)
const currentLength = tweetInput.value.length;
// 第四步:動態更新提示文字內容
counter.innerText = currentLength + " / " + maxLength;
// 第五步:條件判斷 - 檢查是否超過上限
if (currentLength > maxLength) {
// 超過上限:加上紅字警告 Class
counter.classList.add("warning");
tweetInput.classList.add("warning-border");
} else {
// 未超過上限:移除紅字警告 Class,恢復原狀
counter.classList.remove("warning");
tweetInput.classList.remove("warning-border");
}
});</script>
</body>
</html>
第一週的基礎 DOM 觀念(Class 切換、表單控制、清單過濾、折疊選單、字數計數器)我們都學完了!
明天我們會將這幾天學到的東西做成第一個大型綜合實作專案,動手做一個可以動態新增、刪除、標記完成的個人化工具。
【第七課】作品整合 1:綜合練習——個人風格的「待辦事項(To-Do)標籤牆」