问题描述
如何在Javascript和/或jQuery中将函数绑定到左右箭头键?我查看了jQuery的js-hotkey插件(包含内置的绑定函数以添加一个参数来识别特定的键),但它似乎不支持箭头键。
How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function to add an argument to recognize specific keys), but it doesn't seem to support arrow keys.
推荐答案
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
将箭头键的自定义代码放在相应的案例$之间c $ c>和
中断
行。
Put your custom code for the arrow keys between the corresponding case
and break
lines.
由jQuery规范化,因此适用于所有浏览器。对于纯JavaScript方法,请将前两行替换为:
e.which
is normalized by jQuery, so it works in all browsers. For a pure javascript approach, replace the first two lines with:
document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
(编辑2017)
如果你觉得很花哨,你可以使用而不是 e.which
或 e.keyCode
现在。 e.key
正在成为推荐标准,允许您检查字符串:'ArrowLeft'
,'ArrowUp'
,'ArrowRight'
,'ArrowDown'
。新的浏览器本身支持它,。
(edit 2017)
If you feel fancy, you can use e.key
instead of e.which
or e.keyCode
now. e.key
is becoming a recommended standard, allowing you to check against strings: 'ArrowLeft'
, 'ArrowUp'
, 'ArrowRight'
, 'ArrowDown'
. New browsers support it natively, check here.
这篇关于在JS / jQuery中绑定箭头键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!