如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。
当前回答
咖啡和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()
其他回答
而不是使用return false;就像上面的例子一样,你可以使用e.c preventdefault ();这是一样的,但更容易理解和阅读。
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
字符编码:
37 -左 38岁以上 39 -对 40 -下降
纯js右转或左转的例子
window.addEventListener('keydown', function (e) {
// go to the right
if (e.keyCode == 39) {
}
// go to the left
if (e.keyCode == 37) {
}
});
这有点晚了,但热键有一个非常严重的错误,导致事件被执行多次,如果你附加多个热键到一个元素。只需使用纯jQuery。
$(element).keydown(function(ev) {
if(ev.which == $.ui.keyCode.DOWN) {
// your code
ev.preventDefault();
}
});
使用纯Javascript的简洁解决方案(感谢Sygmoral提出的改进建议):
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
};
参见https://stackoverflow.com/a/17929007/1397061。