html 键码在 Firefox 中不起作用

use*_*826 2 html javascript

我有以下代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

目标是让用户可以输入数字、退格键和删除键。它适用于 Chrome 和 IE,但在 Firefox 中,您只能输入数字,而不是退格键或删除键。

JSfiddle:https ://jsfiddle.net/sdy9gd0g/

I a*_*ica 5

为什么不处理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;
    }
  });
})();
Run Code Online (Sandbox Code Playgroud)
<input id="text-box" autofocus>
Run Code Online (Sandbox Code Playgroud)