萬盛學電腦網

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

jQuery 限制 textarea 輸入字數:即時計數與截斷實作

需求場景

微博式輸入框:限制 140 字,即時顯示剩餘字數,超過自動截斷,不使用 `disabled` 避免使用者無法修改。

完整實作

<!DOCTYPE html>
<html>
<head>
  <title>Textarea 字數限制</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(function() {
      var MAX_LEN = 140;
      var $textarea = $("#weibo");
      var $counter = $("#word");

      $textarea.keyup(function() {
        var len = $textarea.val().length;

        // 超過限制:截斷並提示
        if (len > MAX_LEN) {
          $textarea.val($textarea.val().substring(0, MAX_LEN));
          len = MAX_LEN;
        }

        // 更新剩餘字數顯示
        $counter.text(MAX_LEN - len);
      });
    });
  </script>
  <style>
    h6 { color: blue; margin-bottom: 8px; }
    textarea { resize: none; width: 100%; max-width: 400px; height: 80px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 14px; line-height: 1.5; }
    #word { color: #e74c3c; font-weight: bold; }
    .counter { margin-top: 5px; font-size: 13px; color: #666; }
  </style>
</head>
<body>
  <h6>說點什麼吧,你可以輸入 <span>140</span> 個字,現在剩余 <span id="word">140</span> 個</h6>
  <textarea name="con" id="weibo" placeholder="輸入內容..."></textarea>
  <div class="counter">提示:超過限制將自動截斷,不會阻止繼續編輯</div>
</body>
</html>

核心邏輯解析

  1. 事件選擇:`keyup` 在按鍵釋放後觸發,已包含輸入法組合完成的字元。現代建議改用 `input` 事件(涵蓋貼上、拖拽、輸入法、刪除等所有值變更)。
  2. 截斷策略:`substring(0, MAX_LEN)` 保留前 N 字,游標自動停留在末尾,使用者可繼續刪減修改。
  3. 計數顯示:即時回饋剩餘額度,增強使用者掌控感。

現代化改良版 (使用 `input` 事件)

$textarea.on('input', function() {
  var val = this.value;
  var len = val.length;

  if (len > MAX_LEN) {
    this.value = val.substring(0, MAX_LEN);
    len = MAX_LEN;
  }
  $counter.text(MAX_LEN - len);
});

進階功能擴充

1. 區分中英文計算長度 (雙位元字元算 2)

function getByteLength(str) {
  return str.replace(/[^\x00-\xff]/g, 'xx').length; // 中文算 2
}

// 使用
var len = getByteLength(val);
if (len > MAX_BYTES) { /* 截斷邏輯需按位元組處理 */ }

2. 顏色漸變警示

$textarea.on('input', function() {
  var remaining = MAX_LEN - this.value.length;
  var $counter = $('#word').text(remaining);

  if (remaining < 0) $counter.css('color', '#c0392b');
  else if (remaining < 20) $counter.css('color', '#e67e22');
  else if (remaining < 50) $counter.css('color', '#f39c12');
  else $counter.css('color', '#27ae60');
});

3. 顯示目前行數/字元統計

var stats = {
  chars: val.length,
  bytes: getByteLength(val),
  lines: val.split('\n').length,
  words: val.trim() ? val.trim().split(/\s+/).length : 0
};
$('#stats').html(
  '字元: ' + stats.chars + ' | 位元組: ' + stats.bytes +
  ' | 行數: ' + stats.lines + ' | 單詞: ' + stats.words
);

無障礙建議

  • 提供 `aria-describedby` 關聯計數器:`