我正在尝试为我的JQuery应用程序捕获所有关键事件。在使用keydown事件时,我可以获取enter和tab事件,但所有字母都是大写的。因此,我尝试切换到keypress,我听到的是小写+大写字母。这是可行的,只是它不再捕获回车和制表符事件。有没有两全其美的东西?如何捕获所有事件,区分大小写,包括enter、tab、shift、alt等键。
发布于 2016-02-28 02:54:24
在key down event中,调用以event为参数的方法,并添加此行。
e.preventDefault()这将暂停该操作。
谢谢,
发布于 2016-02-28 03:13:14
这样做怎么样?
$(window).on('keydown keypress', function(e) {
e.preventDefault();
var code = e.keyCode || e.which;
console.log(code);
});这在理论上应该做的是防止另一个事件被触发,但因为我们同时调用了keydown和keypress,其中一个事件肯定会被触发。现在,这可能会对代码的其余部分产生负面影响,所以请谨慎使用。
发布于 2016-02-28 03:22:53
希望这对你正在尝试做的事情有所帮助
$(document.body).on('keypress', function(e) {
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
if (valid) {
console.log(keycode + ' keypress'); //printable char on keypress
}
});
$(document.body).on('keyup', function(e) {
var keycode = e.keyCode;
var valid =
(keycode > 47 && keycode < 58) || // number keys
keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns)
(keycode > 64 && keycode < 91) || // letter keys
(keycode > 95 && keycode < 112) || // numpad keys
(keycode > 185 && keycode < 193) || // ;=,-./` (in order)
(keycode > 218 && keycode < 223); // [\]' (in order)
if (!valid) {
console.log(keycode + ' keyup'); //non printable char on keyup
}
});已从此SO link获取可见字符验证
https://stackoverflow.com/questions/35673938
复制相似问题