利用 onkeydown 事件攔截非數字按鍵,結合 onkeyup 處理合法輸入後的業務邏輯。關鍵在於 keydown 先於 keyup 觸發,返回 false 可阻止字符輸入。
<input type="text" value="1" onkeydown="return keyFilter(event)" onkeyup="handleInput(this)" />
function keyFilter(e) {
e = e || window.event;
var code = e.keyCode || e.which;
// 允許:主鍵盤數字(48-57)、小鍵盤數字(96-105)、退格鍵(8)、刪除鍵(46)、方向鍵(37-40)
var allowed =
(code >= 48 && code <= 57) || // 0-9
(code >= 96 && code <= 105) || // NumPad 0-9
code === 8 || // Backspace
code === 46 || // Delete
(code >= 37 && code <= 40); // 方向鍵
// 組合鍵支持
if (e.ctrlKey || e.metaKey) {
// 允許 Ctrl+C/V/A/X/Z/Y 等常用操作
return ['c','v','a','x','z','y'].includes(String.fromCharCode(code).toLowerCase());
}
return allowed;
}
function handleInput(input) {
// 即時業務處理:如格式化、計算等
console.log('當前值:', input.value);
}
input.addEventListener('input', function() {
this.value = this.value.replace(/[^\d]/g, '');
});
優勢:粘貼、拖拽、輸入法輸入等場景均能生效。
<input type="number" min="0" step="1" />
配合 CSS :invalid 可視化提示。
<!-- Vue -->
<input v-model.number="num" @input="val = val.replace(/\\D/g, '')" />
<!-- React -->
<input value={val} onChange={e => setVal(e.target.value.replace(/\\D/g, ''))} />
推薦 input 事件 + 正則過濾作為主防線,keydown 輔助攔截特殊按鍵,並配合 HTML5 type="number" 提供語義化標記。