退格和空格在Firefox中不起作用

Backspace and space not working in Firefox

本文关键字:Firefox 不起作用 空格      更新时间:2023-12-20

我进行了以下验证,以便在Javascript 中只允许数字和小数

function validate(evt) {
      var theEvent = evt || window.event;
      var key = theEvent.keyCode || theEvent.which;           
      key = String.fromCharCode( key );
      var regex = /[0-9]|'./;
      if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
      }
}

我在我的文本框元素中称之为onkeypress='validate(event)'

这段代码在IE中运行良好,但当我在Firefox backspace中尝试同样的操作时,左右箭头键和空格都不起作用。

我该怎么解决这个问题?

使用按键是正确的解决方案,但您只需要通过JS附加事件处理程序(无论如何,这被认为是更好的做法),并使用类似的东西:

$('#myInput').keypress(function(event){
   validate(event)
});
function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;           
  if (key <48 || key > 57  || key == 190)//keycode is a number between 0 and 9 or '.'
       ...
};

使用keyupkeydown而不是keypress

keypress只有在有字符插入时才应该触发

http://www.quirksmode.org/dom/events/keys.html

keydown函数可以在所有浏览器中使用。请使用按键功能,它会工作!

示例:-

$(document).keydown(function (e){
                    if(e.keyCode == 37) // left arrow
                    {
                    //code for left arrow
                    }
                    else if(e.keyCode == 39)    // right arrow
                    {
                   //code for right arrow
                    }
                    });

尝试

    //allows number and hyphen only 
    function isNumeric(e)
    {
        var a = e.charCode;
        if(a==0){return;}
        return ((a >= 48 && a <= 57));
    }
    </script>

Firefox Backspace charcode 0。