萬盛學電腦網

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

JavaScript 限制 Textarea 字符長度並即時顯示剩餘字數實戰

表單驗證中限制輸入長度並實時反饋剩餘字數是提升用戶體驗的關鍵細節。本文從基礎實現到生產級組件,層層遞進講解 Textarea 字符計數與限制的最佳實踐,涵蓋中英文混輸、粘貼處理、無障礙支持等實戰細節。

基礎實現:核心邏輯

function textCounter(field, countField, maxLimit) {
  // 1. 截斷超出部分
  if (field.value.length > maxLimit) {
    field.value = field.value.substring(0, maxLimit);
  }
  // 2. 更新剩餘字數顯示
  countField.value = maxLimit - field.value.length;
}

HTML 綁定

<form name="myform">
  <textarea 
    name="message" 
    cols="28" 
    rows="5" 
    onkeydown="textCounter(this, this.form.remLen, 200)" 
    onkeyup="textCounter(this, this.form.remLen, 200)"
    onpaste="setTimeout(() => textCounter(this, this.form.remLen, 200), 0)"
  ></textarea>
  <span>剩餘字數:</span>
  <input name="remLen" type="text" value="200" size="4" readonly />
</form>

關鍵事件選擇說明

事件觸發時機用途
keydown按鍵按下(字符未入框)攔截超長輸入(配合 keyup)
keyup按鍵彈起(字符已入框)更新計數器、截斷多餘字符
input內容發生變化(推薦)覆蓋鍵盤、粘貼、拖拽、自動填充等所有輸入方式
paste粘貼後異步處理剪貼板內容(需 setTimeout 0)

現代最佳實踐:單獨監聽 input 事件即可覆蓋所有輸入場景,無需同時綁定 keydown/keyup。

進階版:字符/字節雙模式計數組件

中文佔 2 字節、英文佔 1 字節的業務場景常見於短信、數據庫字段限制。

class TextCounter {
  constructor(textarea, options = {}) {
    this.textarea = textarea;
    this.maxChars = options.maxChars || 200;
    this.maxBytes = options.maxBytes; // 可選:字節限制
    this.counterEl = options.counterEl; // 顯示元素
    this.mode = options.mode || 'chars'; // 'chars' | 'bytes'
    this.init();
  }

  init() {
    // 初始化顯示
    this.updateCounter();
    
    // 核心監聽:input 事件覆蓋所有輸入方式
    this.textarea.addEventListener('input', () => this.handleInput());
    
    // 可選:阻止超長輸入的視覺反饋
    this.textarea.addEventListener('keydown', e => {
      if (this.getLength(this.textarea.value) >= this.getLimit() && !this.isControlKey(e)) {
        e.preventDefault();
      }
    });
  }

  handleInput() {
    const value = this.textarea.value;
    const limitedValue = this.enforceLimit(value);
    
    if (limitedValue !== value) {
      // 保持光標位置
      const start = this.textarea.selectionStart;
      this.textarea.value = limitedValue;
      this.textarea.setSelectionRange(start, start);
    }
    
    this.updateCounter();
  }

  getLength(str) {
    if (this.mode === 'bytes') {
      // 計算 UTF-8 字節長度:中文 3 字節,英文 1 字節
      // 若業務定義中文 2 字節,可用:str.replace(/[^\x00-\xff]/g, 'aa').length
      return new TextEncoder().encode(str).length;
    }
    return str.length;
  }

  getLimit() {
    return this.mode === 'bytes' ? this.maxBytes : this.maxChars;
  }

  enforceLimit(str) {
    const limit = this.getLimit();
    if (this.getLength(str) <= limit) return str;
    
    // 二分查找最大合法長度(性能優於逐字符截取)
    let low = 0, high = str.length;
    while (low < high) {
      const mid = Math.ceil((low + high) / 2);
      if (this.getLength(str.substring(0, mid)) <= limit) {
        low = mid;
      } else {
        high = mid - 1;
      }
    }
    return str.substring(0, low);
  }

  isControlKey(e) {
    // 允許控制鍵:Backspace, Delete, 方向鍵, Ctrl/Cmd+A/C/V/X/Z 等
    return ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Tab', 'Escape'].includes(e.key) ||
           (e.ctrlKey || e.metaKey) && ['a', 'c', 'v', 'x', 'z', 'y'].includes(e.key.toLowerCase());
  }

  updateCounter() {
    if (!this.counterEl) return;
    const remaining = Math.max(0, this.getLimit() - this.getLength(this.textarea.value));
    this.counterEl.textContent = `${remaining}`;
    
    // 視覺狀態反饋
    this.counterEl.classList.toggle('warning', remaining < this.getLimit() * 0.1);
    this.counterEl.classList.toggle('danger', remaining === 0);
  }
}

// 使用示例
const textarea = document.querySelector('textarea[name="message"]');
const counterDisplay = document.querySelector('.char-counter span');

new TextCounter(textarea, {
  maxChars: 200,
  counterEl: counterDisplay,
  mode: 'chars'
});

// 或字節模式(如短信 70 字/67 字計費)
new TextCounter(textarea, {
  maxBytes: 140, // 70 個中文字符 ≈ 210 字節,視編碼而定
  counterEl: counterDisplay,
  mode: 'bytes'
});

CSS 樣式建議

.char-counter {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}
.char-counter.warning { color: #e6a23c; }
.char-counter.danger { color: #f56c6c; font-weight: bold; }
textarea.over-limit {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

無障礙與用戶體驗細節

  • ARIA 屬性:aria-describedby 關聯計數器 ID,屏幕閱讀器可播報剩餘字數。
  • 視覺反饋:接近限制時變黃,超限/達限變紅,邊框高亮提示。
  • 保留光標:截斷時通過 selectionStart/End 維持光標位置,避免跳動。
  • 服務端二次驗證:前端限制只能阻擋誤操作,**後端必須再次校驗長度**,防止繞過前端限制。

常見坑點避雷

  • onkeypress 已棄用,且無法捕獲中文輸入法組合字過程,請使用 input 事件。
  • maxlength 屬性(HTML5)可原生限制字符數,但無法區分字符/字節、無法自定義超限提示、無法統計剩餘字數,僅適合極簡場景。
  • 中文輸入法組合字階段(compositionstart/compositionend)下 input 事件不觸發,需配合 compositionend 處理,上述 TextCounter 類已隱式兼容(組合字確認後觸發 input)。

總結

從簡單的 onkeyup 到功能完善的 TextCounter 類,字符限制組件的演進體現了前端工程化思維:封裝復用、關注點分離、兼容性處理、無障礙支持、性能優化。根據項目復雜度選擇合適層級的方案,細節決定體驗質量。

copyright © 萬盛學電腦網 all rights reserved