javascript 如何在jquery中获得右,左,上和下箭头键值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20121252/
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
How to get right, left, up and bottom arrow key value in jquery
提问by Bharathi
I have used the below code, and whenever click the arrow key(left, right, up, down) i get the key value is "0". anyone can help on this?
我使用了下面的代码,每当单击箭头键(向左、向右、向上、向下)时,我都会得到键值为“0”。任何人都可以帮忙吗?
$(document).keypress(function (e) {
alert("key value: " + e.which);
});
How to get (Up, Down, Right, Left) arrow key value when keypress.
按键时如何获取(向上,向下,向右,向左)箭头键值。
回答by Sarath
Use keydown
insted of keypress
使用keydown
插入keypress
$(document).keydown(function(event){
var key = event.which;
switch(key) {
case 37:
// Key left.
break;
case 38:
// Key up.
break;
case 39:
// Key right.
break;
case 40:
// Key down.
break;
}
});
回答by James Donnelly
In many browsers the keypress
event doesn't recognise the arrow keys (nor keys like "shift", "del", "esc", etc. If you want to capture those key presses, you'll need to use keydown
or keyup
instead:
在许多浏览器中,该keypress
事件无法识别箭头键(也无法识别“shift”、“del”、“esc”等键。如果您想捕获这些按键,您需要使用keydown
或keyup
代替:
$(document).keydown(function (e) {
alert("key value: " + e.which);
});
As for the right, left, up and down arrow keys, those are:
至于右、左、上、下方向键,分别是:
left 37
up 38
right 39
down 40