← 返回完整题库
HTML简单

如何控制 input 输入框的输入字数?

参考答案

分三个层次:

1. 原生属性(首选)

  • maxlength="10":限制字符数(type 为 text/password/search/tel/url/email 等有效,**number 类型无效**),粘贴超长会被截断,部分浏览器有输入法保护。
  • minlength:提交时的最小长度校验。
  • 数值范围用 min/max/step,而不是 maxlength。
  • 表单校验用 required、pattern + checkValidity()/setCustomValidity()。

2. JS 动态限制(需要计数提示时)

input.addEventListener('input', e => {
  const max = 20;
  if (e.target.value.length > max) {
    e.target.value = e.target.value.slice(0, max);
  }
  counter.textContent = `${e.target.value.length}/${max}`;
});

中文输入法坑:拼音输入过程中 input 会带拼音字母,直接截断会打断输入。用 compositionstart/compositionend 标记 isComposing(或读 e.isComposing),合成期间不截断:

input.addEventListener('compositionend', () => { forceLimit(input); });

3. 字符计数口径

value.length 是 UTF-16 码元数,emoji 算 2、部分汉字扩展字符也算 2;要按「人眼字符」计数用 [...value].length 或 Intl.Segmenter 按字素切分,否则计数与业务(如微博字数)不一致。

补充

  • CSS 无法限制输入长度(max-width 只改外观);
  • 需要纯数字/去空格用 inputmode="numeric" + 正则过滤;
  • 截断时注意保留光标位置(记录 selectionStart 并在赋值后恢复)。

本题来自 计算机知识面试题库,共 921 道题。