如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。
当前回答
这有点晚了,但热键有一个非常严重的错误,导致事件被执行多次,如果你附加多个热键到一个元素。只需使用纯jQuery。
$(element).keydown(function(ev) {
if(ev.which == $.ui.keyCode.DOWN) {
// your code
ev.preventDefault();
}
});
其他回答
你可以使用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/
$(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;
}
});
在这里检查上面的例子。
咖啡和Jquery
$(document).on 'keydown', (e) ->
switch e.which
when 37 then console.log('left key')
when 38 then console.log('up key')
when 39 then console.log('right key')
when 40 then console.log('down key')
e.preventDefault()
你可以通过以下方法检查箭头键是否被按下:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41) {
alert( "arrowkey pressed" );
return false;
}
});