Windows键盘键码无法正常工作

时间:2016-08-23 21:11:16

标签: jquery windows

我在文本输入中添加了一个简单的掩码,只允许输入数字。我使用以下代码完成了它:

jQuery(function($) {
        $("#zip").keydown(function(event) {
            // Allow only backspace and delete
            if ( event.keyCode == 46 || event.keyCode == 8 ) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.keyCode < 48 || event.keyCode > 57 ) {
                    event.preventDefault(); 
                }   
            }
        });
    });

我遇到的问题是键盘号码无法在Windows上运行(它们可以在Mac上找到)。但是,键盘顶行的数字可以正常工作。有没有人遇到过这个?

2 个答案:

答案 0 :(得分:1)

您可以使用:

jQuery(function($) {
        $("#zip").keydown(function(event) {
            var code = e.keycode || e.which
            // Allow only backspace and delete
            if ( code  == 46 || code  == 8 ) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (code  < 48 || code  > 57 ) {
                    event.preventDefault(); 
                }   
            }
        });
    });

答案 1 :(得分:1)

您没有在if语句中包含numberpad的键码。这应该有效:

jQuery(function($) {
    $("#zip").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57 ) && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault(); 
            }   
        }
    });
});