表單驗證中限制文字輸入長度並即時回饋剩餘字數,是提升使用者體驗的關鍵細節。本文提供原生 JS 與 jQuery 兩種實作,並處理中英文混輸、貼上、拖曳等邊界情況。
<textarea id="message" maxlength="200" rows="5" cols="40"></textarea>
<div class="counter">
<span id="remaining">200</span> / 200 字
</div>
<script>
const textarea = document.getElementById('message');
const remainingEl = document.getElementById('remaining');
const MAX = 200;
// 統一更新計數器
function updateCounter() {
const len = textarea.value.length;
const remaining = Math.max(0, MAX - len);
remainingEl.textContent = remaining;
// 視覺回饋
remainingEl.parentElement.classList.toggle('warning', remaining < 20);
remainingEl.parentElement.classList.toggle('danger', remaining === 0);
// 超過限制截斷(雖然 maxlength 已原生阻擋,但貼上時可能短暫超過)
if (len > MAX) {
textarea.value = textarea.value.slice(0, MAX);
updateCounter(); // 遞歸修正
}
}
// 監聽所有可能改變值的事件
['input', 'propertychange', 'paste', 'cut', 'drop'].forEach(evt => {
textarea.addEventListener(evt, updateCounter);
});
// 初始化
updateCounter();
</script>
.counter { text-align: right; margin-top: 4px; font-size: 0.875rem; color: #666; }
.counter.warning { color: #f0ad4e; }
.counter.danger { color: #d9534f; font-weight: bold; }
$('#message').on('input propertychange paste cut drop', function() {
const max = 200;
const len = this.value.length;
const remaining = Math.max(0, max - len);
$('#remaining').text(remaining).toggleClass('warning', remaining < 20).toggleClass('danger', remaining === 0);
if (len > max) this.value = this.value.slice(0, max);
});
若需求為「中文 1 字、英文 0.5 字」或類似計算:
function getCharCount(str) {
// 中日韓統一表意文字、全形符號視為 1,其餘 0.5
let count = 0;
for (const ch of str) {
const code = ch.charCodeAt(0);
// 簡易判斷:CJK 統一表意文字區塊 + 全形符號區塊
if ((code >= 0x4e00 && code <= 0x9fff) || // CJK Unified Ideographs
(code >= 0x3000 && code <= 0x303f) || // CJK Symbols
(code >= 0xff00 && code <= 0xffef)) { // Halfwidth and Fullwidth Forms
count += 1;
} else {
count += 0.5;
}
}
return Math.ceil(count); // 或保留小數
}
// 使用
function updateCounterAdvanced() {
const count = getCharCount(textarea.value);
const remaining = Math.max(0, MAX - count);
// ...
}
maxlength` 屬性<textarea maxlength="200"></textarea>
let isComposing = false;
textarea.addEventListener('compositionstart', () => isComposing = true);
textarea.addEventListener('compositionend', e => {
isComposing = false;
// 合成結束時更新
updateCounter();
});
// input 事件中跳過合成中狀態(避免未確認文字計入)
textarea.addEventListener('input', e => {
if (!isComposing) updateCounter();
});
form.addEventListener('submit', e => {
if (textarea.value.length > MAX) {
e.preventDefault();
textarea.focus();
alert(`內容超過 ${MAX} 字元限制,請刪減後再送出。`);
}
});
結合原生 `maxlength`、完整事件監聽、視覺回饋與提交驗證,即可打造強健且友善的文字長度限制體驗。