如何在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/
其他回答
我只是把其他答案中最好的部分结合起来:
$(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绑定:
$(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');
}
});
纯js右转或左转的例子
window.addEventListener('keydown', function (e) {
// go to the right
if (e.keyCode == 39) {
}
// go to the left
if (e.keyCode == 37) {
}
});
我来这里是为了寻找一种简单的方法,让用户在关注一个输入时,使用方向键来+1或-1一个数字输入。我从来没有找到一个好的答案,但使下面的代码,似乎工作得很好-使这个网站范围现在。
$("input").bind('keydown', function (e) {
if(e.keyCode == 40 && $.isNumeric($(this).val()) ) {
$(this).val(parseFloat($(this).val())-1.0);
} else if(e.keyCode == 38 && $.isNumeric($(this).val()) ) {
$(this).val(parseFloat($(this).val())+1.0);
}
});
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的示例。键,以获得更现代的检测方向键的解决方案。