C# ASP.NET:用户按键校验及输入字符精准定位
实现带格式约束的时间输入框(初始值00:00)
核心需求是打造一个严格遵循HH:MM格式的输入框,初始值为00:00,用户输入数字时自动填充到对应位置,无需手动输入冒号,同时保持格式不被破坏。
实现代码
HTML
<input type="text" id="timeInput" value="00:00" maxlength="5" autocomplete="off">
JavaScript
const timeInput = document.getElementById('timeInput'); timeInput.addEventListener('keydown', function(e) { // 仅允许数字键和退格键操作 const allowedKeys = ['0','1','2','3','4','5','6','7','8','9','Backspace']; if (!allowedKeys.includes(e.key)) { e.preventDefault(); return; } const currentValue = this.value; const cursorPos = this.selectionStart; // 处理退格逻辑 if (e.key === 'Backspace') { if (cursorPos !== 2) { // 光标不在冒号位置时,替换当前位为0并左移光标 const newValue = currentValue.substring(0, cursorPos - 1) + '0' + currentValue.substring(cursorPos); this.value = newValue; this.setSelectionRange(cursorPos - 1, cursorPos - 1); } else { // 光标在冒号位置时,直接左移到前一位 this.setSelectionRange(1, 1); } e.preventDefault(); return; } // 处理数字输入逻辑 let newValue = currentValue; let newCursorPos = cursorPos; if (cursorPos < 2) { // 填充小时位,输入后自动跳转光标 newValue = newValue.substring(0, cursorPos) + e.key + newValue.substring(cursorPos + 1); newCursorPos = cursorPos === 1 ? 3 : cursorPos + 1; } else if (cursorPos > 2) { // 填充分钟位,输入后自动跳转光标 newValue = newValue.substring(0, cursorPos) + e.key + newValue.substring(cursorPos + 1); newCursorPos = cursorPos === 4 ? 4 : cursorPos + 1; } else { // 光标停在冒号位置时,自动跳转到分钟第一位填充 newCursorPos = 3; newValue = newValue.substring(0, newCursorPos) + e.key + newValue.substring(newCursorPos + 1); } this.value = newValue; this.setSelectionRange(newCursorPos, newCursorPos); e.preventDefault(); }); // 聚焦时自动选中第一个小时位,提升输入效率 timeInput.addEventListener('focus', function() { this.setSelectionRange(0, 0); });
关键特性说明
- 格式锁死:输入框固定长度为5,始终保持
HH:MM结构,冒号无法被修改或删除 - 按键过滤:仅开放数字键和退格键,避免无效输入破坏格式
- 自动导航:输入数字后自动跳转到下一个可输入位置,退格时自动回退并补0,全程无需手动调整光标
- 初始状态:默认值为
00:00,聚焦时自动选中第一个小时位,方便快速输入
内容的提问来源于stack exchange,提问作者Chris Glenn
相关产品推荐
相关产品推荐

