[英]How do I create a keyboard event that lets me only use the backspace and numbers (on top of keyboard and numpad)?
function handleSpinnerInput(event) {
var keyID = event.keyCode
if (keyID < 48 || keyID > 57 ) {
/*
* If it isn't a number, pretend the key was never pressed at all. This
* key range works for both the number pad and the numbers on the top of
* the keyboard. I've tested this on IE, Firefox, and Chrome to verify
* it works on the latest version. However, I need this to work on Firefox v.31.
*/
event.preventDefault();
return false;
}
}
I am using the onkeydown() function to invoke on an input field but only the top number of the keyboard work and it doesn't even let me type the backspace in the older version.我正在使用 onkeydown() function 在输入字段上调用,但只有键盘的顶部数字起作用,它甚至不允许我在旧版本中输入退格键。 I see that the numpad keycodes are 96-105 and the backspace keycode is 46. how would I include that in my conditional and should I set it to ignore keycodes that are not the ones specified?我看到小键盘键码是 96-105,退格键码是 46。我如何将它包含在我的条件中,我应该将其设置为忽略未指定的键码吗?
EDIT: the code in top worked with the onkeypress() function but I have since changed it to onkeydown() since it didnt work on older firefox.编辑:顶部的代码与 onkeypress() function 一起使用,但我已将其更改为 onkeydown(),因为它不适用于较旧的 firefox。
EDIT: function handleSpinnerInput(event) {编辑:function handleSpinnerInput(event) {
var keyCode = event.keyCode ;
if(!(Number(keyCode) >= 0 && Number(keyCode) <= 9) && keyCode != 'Backspace')
event.preventDefault();
return false;
}
} }
Use:利用:
let input = document.querySelector('input') input.addEventListener('keydown', handleSpinnerInput) function handleSpinnerInput(event) { if(.(Number(event.key) >= 0 && Number(event.key) <= 9) && event.key != 'Backspace') // Checks whether the key is different from the number or backspace event.preventDefault() }
<input type="text">
OR或者
function handleSpinnerInput(event) { console.log(event.keyCode) let isNumber = (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 || event.keycode <= 105) let backspace = event.keyCode == 46 if(.isNumber && !backspace) event.preventDefault() }
<input type="text" onkeydown="handleSpinnerInput(event)">
Doubts?怀疑? comment评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.