<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>字符限制輸入框</title>
<style>
.counter { color: #666; font-size: 14px; margin-top: 5px; }
.counter.warning { color: #f00; }
textarea { width: 100%; max-width: 500px; height: 120px; padding: 10px; box-sizing: border-box; }
</style>
</head>
<body>
<textarea id="msgInput" maxlength="200" placeholder="最多輸入 200 字符"></textarea>
<div class="counter" id="counter">還可輸入 <span id="remain">200</span> 字符</div>
<script>
const textarea = document.getElementById('msgInput');
const remainEl = document.getElementById('remain');
const counterEl = document.getElementById('counter');
const MAX = 200;
function updateCounter() {
const len = textarea.value.length;
const remain = Math.max(0, MAX - len);
remainEl.textContent = remain;
counterEl.classList.toggle('warning', remain < 20);
}
// 輸入事件:覆蓋 keydown/keyup/input/paste
textarea.addEventListener('input', updateCounter);
// 初始化
updateCounter();
</script>
</body>
</html>
input 事件在所有輸入方式(鍵盤、粘貼、拖拽、輸入法組合字)後觸發,覆蓋面最全。
原生屬性可阻止超長輸入,但無剩餘提示,需 JS 配合。
若需區分(中文 2 字節、英文 1 字節):
function getByteLength(str) {
let len = 0;
for (let i = 0; i < str.length; i++) {
len += str.charCodeAt(i) > 255 ? 2 : 1;
}
return len;
}
form.addEventListener('submit', e => {
if (textarea.value.length > MAX) {
e.preventDefault();
alert(`內容超過 ${MAX} 字符限制`);
textarea.focus();
}
});
// Vue 3 Composition API 示例
export function useTextCounter(maxLength) {
const text = ref('');
const remain = computed(() => Math.max(0, maxLength - text.value.length));
const isWarning = computed(() => remain.value < maxLength * 0.1);
return { text, remain, isWarning };
}