如何在Javascript和/或jQuery中绑定函数到左和右方向键?我查看了jQuery的js-hotkey插件(包装了内置的bind函数以添加一个参数来识别特定的键),但它似乎不支持方向键。
当前回答
你确定jQuery。热键不支持方向键?我之前摆弄过他们的演示,当我在IE7、Firefox 3.5.2和谷歌Chrome 2.0.172中测试它时,观察到左右上下工作正常……
编辑:它出现jquery。热键已重新定位到Github: https://github.com/jeresig/jquery.hotkeys
其他回答
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
字符编码:
37 -左 38岁以上 39 -对 40 -下降
防止箭头只适用于任何对象之外的选择,实际上我还没有在另一个对象上测试LOL。 但它可以停止页面和输入类型上的箭头事件。
我已经尝试阻止箭头左右改变选择对象的值使用“e.c preventdefault()”或“返回false”在“kepress”“keydown”和“keyup”事件,但它仍然改变对象的值。但是事件仍然告诉你箭头被按下了。
纯js右转或左转的例子
window.addEventListener('keydown', function (e) {
// go to the right
if (e.keyCode == 39) {
}
// go to the left
if (e.keyCode == 37) {
}
});
咖啡和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()
你可以使用jQuery绑定:
$(window).bind('keydown', function(e){
if (e.keyCode == 37) {
console.log('left');
} else if (e.keyCode == 38) {
console.log('up');
} else if (e.keyCode == 39) {
console.log('right');
} else if (e.keyCode == 40) {
console.log('down');
}
});