Javascript键码在Firefox中不起作用,但在chrome中运行良好

Javascript keycodes not working in firefox but works well in chrome

本文关键字:chrome 运行 但在 不起作用 键码 Firefox Javascript      更新时间:2023-09-26

我只是在做我的表单验证,其中电话号码必须只是数字!该代码在chrome中运行良好,但在Firefox和IE中则不然。请给我一些解决方案

我的代码如下

function noLet(event) {
    if (event.keyCode == 46 || event.keyCode==8 || event.keyCode > 47 && event.keyCode <      58) {
        event.returnValue = true;
    } 
    else {
        event.returnValue = false;
    }
}

.HTML:

 onkeypress="noLet(e)"><label id="mobph"></label><font 
size="1"><br>Max 10 numbers only allowed!</font> 

我可以建议以下代码来解决您的问题。这就是我正在做的。经过测试,就像 ie、chrome 和 firefox 中的魅力一样工作:

//return numbers and backspace(charCode == 8) only
function noLet(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode >= 48 && charCode <= 57 || charCode == 8)
        return true;
    return false;

您可以使用键/字符代码来检测按下的键是数字还是数字。首先,您必须检测跨浏览器的键/字符代码是什么(请记住使用 event.keypress 作为您的事件以进一步确保兼容性(。之后,将其从其十进制值转换为其字符。然后,您可以使用parseInt()将其解析为整数,如果函数中的第一个值无法解析为 int,它将返回NaN。然后阻止默认操作(如果它NaN(。

var numbersOnly = function(e){
    var charCode = (typeof e.which === "number") ? e.which : e.keyCode,
        chr = String.fromCharCode(charCode);
    if(isNaN(parseInt(chr, 10))) e.preventDefault();
}
<input type="text" name="phoneNumber" onkeypress="numbersOnly(event);">

因为至少在 Firefox 上,它是 charCode ,而不是在按键处理程序中keyCode,并且"returnValue"被忽略(调用preventDefault()停止插入(。

浏览器

存在兼容性问题。这是我在某些RND中发现的解决方案。希望它会以某种方式帮助你;点击这里