我有以下代码:
function noNumbers(e)
{
var charCode = (e.which) ? e.which :
((e.charCode) ? e.charCode :
((e.keyCode) ? e.keyCode : 0));
if((charCode < 48 || charCode > 57) && (charCode > 45 || charCode < 47))
e.preventDefault();
}
目标是让用户可以键入数字、退格键和删除键。它适用于 Chrome 和 IE,但在 Firefox 中,您可以只键入数字,而不是退格键或删除键。
JSfiddle:https://jsfiddle.net/sdy9gd0g/
最佳答案
为什么不处理 input
事件代替?此方法将通过键盘输入、剪切、粘贴等方式处理实时更改。
(function() {
var textBox = document.getElementById("text-box");
textBox.addEventListener("input", function(e) {
var val = this.value,
rx = /[^\d]/g;
if (rx.test(val)) {
var pos = this.selectionStart;
this.value = val.replace(rx, "");
this.selectionStart = pos;
this.selectionEnd = pos - 1;
}
});
})();
<input id="text-box" autofocus>
关于javascript - html 键码在 firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168918/