jQuery 向上键/向下键按键检测不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17412033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery up key / down key keypress detection not working?
提问by SB2055
In the following code:
在以下代码中:
$(document).keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 40) {
alert("down pressed");
} else if (code == 38) {
alert("up pressed");
}
});
I'm trying to detect if the down key or up key is pressed. Why isn't it working?
我试图检测是否按下了向下键或向上键。为什么它不起作用?
Fiddlehttp://jsfiddle.net/K9uDn/10/
小提琴http://jsfiddle.net/K9uDn/10/
I'm in chrome
我在铬
回答by Aguardientico
Use keydowninstead of keypress, some browsers does not fire keypresswhen an "special key (like arrows)" are pressed
使用keydown而不是keypress,某些浏览器在按下“特殊键(如箭头)”时不会触发keypress
回答by theftprevention
jQuery's keypress
method isn't very stable. Use on('keydown')
instead.
jQuery 的keypress
方法不是很稳定。使用on('keydown')
来代替。
回答by John Aho
Here's the Fiddleof a fixed version of the javascript code with extra buttons trapped using a switch/case statement
这是固定版本的 javascript 代码的小提琴, 带有使用 switch/case 语句捕获的额外按钮
$(document).on('keydown',function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
switch (code){
case 34:
alert("Page down pressed");
break;
case 33:
alert("Page up pressed");
break;
case 40:
alert("Down pressed");
break;
case 38:
alert("Up pressed");
break;
case 37:
alert("Left pressed");
break;
case 39:
alert("Right pressed");
break;
}
回答by Clem
on('keyup') does not work in IE. Not in version 9 at least.
on('keyup') 在 IE 中不起作用。至少在版本 9 中没有。