萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 限制 textarea 輸入字符數並即時顯示剩餘字數

核心功能

  • 即時統計輸入字符數
  • 超過限制自動截斷
  • 顯示剩餘可輸入字數
  • 支援中英文混合(按字符計算)

完整實現

<!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>

關鍵點解析

1. 使用 input 事件而非 keyup/keydown

input 事件在所有輸入方式(鍵盤、粘貼、拖拽、輸入法組合字)後觸發,覆蓋面最全。

2. HTML5 maxlength 屬性

原生屬性可阻止超長輸入,但無剩餘提示,需 JS 配合。

3. 中英文統一按字符計算

若需區分(中文 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();
    }
});

React/Vue 組件化思路


// 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 };
}
copyright © 萬盛學電腦網 all rights reserved