如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。
当前回答
你可以使用KeyboardJS。我为这样的任务编写了库。
KeyboardJS.on('up', function() { console.log('up'); });
KeyboardJS.on('down', function() { console.log('down'); });
KeyboardJS.on('left', function() { console.log('right'); });
KeyboardJS.on('right', function() { console.log('left'); });
在这里签出库=> http://robertwhurst.github.com/KeyboardJS/
其他回答
一个健壮的Javascript库,用于捕获键盘输入和输入的组合键。它没有依赖关系。
http://jaywcjlove.github.io/hotkeys/
hotkeys('right,left,up,down', function(e, handler){
switch(handler.key){
case "right":console.log('right');break
case "left":console.log('left');break
case "up":console.log('up');break
case "down":console.log('down');break
}
});
你可以通过以下方法检查箭头键是否被按下:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41) {
alert( "arrowkey pressed" );
return false;
}
});
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
字符编码:
37 -左 38岁以上 39 -对 40 -下降
你可以使用方向键的keyCode(37,38,39和40表示左,上,右和下):
$('.selector').keydown(function (e) {
var arrow = { left: 37, up: 38, right: 39, down: 40 };
switch (e.which) {
case arrow.left:
//..
break;
case arrow.up:
//..
break;
case arrow.right:
//..
break;
case arrow.down:
//..
break;
}
});
在这里检查上面的例子。
document.onkeydown = 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)
};
如果需要支持IE8,则函数体以e = e || window.event;开关(e。其中|| e.keyCode){。
2020年(编辑) 注意KeyboardEvent。现在已经弃用了。请参阅使用KeyboardEvent的示例。键,以获得更现代的检测方向键的解决方案。