
本文详解为何otp输入框的`change`事件无法触发自动聚焦,以及如何改用`input`或`keyup`事件正确实现6位数字逐位跳转的交互逻辑。
在构建动态生成的6位OTP(One-Time Password)输入组件时,一个常见需求是:用户在某一位输入数字后,焦点自动移至下一位输入框。然而,若错误地依赖 change 事件来驱动 focus() 和 blur() 操作,该逻辑将无法按预期工作——因为 change 事件仅在输入框失去焦点(blur)且值发生变更后才触发,而非实时响应输入行为。
✅ 正确做法:使用 input 事件替代 change
input 事件会在 元素的值每次变化时立即触发(包括键盘输入、粘贴、剪切等),非常适合 OTP 的实时跳转场景。以下是优化后的核心代码逻辑(已修复原问题):
const OTP_LENGTH = 6;
const textInputs = [];
const otpContainer = document.getElementById('otp-container');
for (let i = 0; i < OTP_LENGTH; i++) {
const input = document.createElement('input');
input.type = 'text'; // 推荐用 text + inputmode="numeric" 更兼容
input.inputMode = 'numeric'; // 移动端唤起数字键盘
input.maxLength = 1; // 注意:用 maxLength 属性,非 max-length(后者无效)
input.id = `otp-input-${i}`; // 避免重复ID(原代码中所有input id均为'otp-input',违反HTML规范)
input.dataset.otpPos = i;
input.addEventListener('input', function (e) {
const target = e.target;
const position = parseInt(target.dataset.otpPos, 10);
const value = target.value.replace(/\D/g, ''); // 过滤非数字字符
target.value = value; // 确保只保留数字
// 若当前有输入且未到末位,则聚焦下一位
if (value && position < OTP_LENGTH - 1) {
textInputs[position + 1].focus();
}
});
// 可选:支持退格键回退到上一位
input.addEventListener('keydown', function (e) {
if (e.key === 'Backspace' && !this.value && this.previousElementSibling) {
this.previousElementSibling.focus();
}
});
textInputs.push(input);
otpContainer.appendChild(input);
}
// 自动聚焦第一位(提升用户体验)
if (textInputs[0]) textInputs[0].focus();⚠️ 关键注意事项
- 避免重复 ID:HTML 中 id 必须唯一。原代码中所有 均设为 id="otp-input",会导致 document.getElementById 行为不可预测,也影响可访问性(a11y)。应使用 id="otp-input-0" 等唯一标识。
- maxLength 是属性,不是 max-length:setAttribute('max-length', '1') 无效;应直接赋值 input.maxLength = 1 或 input.setAttribute('maxlength', '1')(注意大小写)。
- type="number" 的陷阱:虽能限制输入类型,但存在兼容性问题(如 iOS Safari 允许输入字母、长按出现增减按钮、value 可能为 "" 或 "0" 导致逻辑异常)。推荐使用 type="text" + inputmode="numeric" + 正则过滤,更可控。
- focus() 失效的常见原因:
✅ 补充增强体验(可选)
- 添加 autocomplete="one-time-code" 提升密码管理器识别率;
- 使用 aria-label 标注每位输入框(如 "OTP digit 1 of 6")以增强无障碍支持;
- 对粘贴内容做分段处理(如粘贴 "123456" 自动填充全部6位)。
通过将事件监听从 change 切换至 input,并修正 DOM 属性与结构规范,即可稳定实现动态 OTP 输入框的无缝聚焦流转——既符合 Web 标准,又兼顾多端兼容性与用户体验。










