如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。
当前回答
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
字符编码:
37 -左 38岁以上 39 -对 40 -下降
其他回答
你可以使用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/
这有点晚了,但热键有一个非常严重的错误,导致事件被执行多次,如果你附加多个热键到一个元素。只需使用纯jQuery。
$(element).keydown(function(ev) {
if(ev.which == $.ui.keyCode.DOWN) {
// your code
ev.preventDefault();
}
});
我只是把其他答案中最好的部分结合起来:
$(document).keydown(function(e){
switch(e.which) {
case $.ui.keyCode.LEFT:
// your code here
break;
case $.ui.keyCode.UP:
// your code here
break;
case $.ui.keyCode.RIGHT:
// your code here
break;
case $.ui.keyCode.DOWN:
// your code here
break;
default: return; // allow other keys to be handled
}
// prevent default action (eg. page moving up/down)
// but consider accessibility (eg. user may want to use keys to choose a radio button)
e.preventDefault();
});
你确定jQuery。热键不支持方向键?我之前摆弄过他们的演示,当我在IE7、Firefox 3.5.2和谷歌Chrome 2.0.172中测试它时,观察到左右上下工作正常……
编辑:它出现jquery。热键已重新定位到Github: https://github.com/jeresig/jquery.hotkeys
你可以使用方向键的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;
}
});
在这里检查上面的例子。