问题
This question already has an answer here:
- Binding arrow keys in JS/jQuery 16 answers
I want to give my content slider the ability to respond to keypress (LEFT ARROW key and RIGHT ARROW key) feature. I have read about some conflicts between several browsers and operation systems.
The user can navigate the content while he is on the global website (body).
Pseudo Code:
ON Global Document
IF Key Press LEFT ARROW
THEN animate #showroom css 'left' -980px
IF Key Press RIGHT ARROW
THEN animate #showroom css 'left' +980px
I need a solution without any crossover (Browsers, OSs) conflicts.
回答1:
$("body").keydown(function(e) {
if(e.keyCode == 37) { // left
$("#showroom").animate({
left: "-=980"
});
}
else if(e.keyCode == 39) { // right
$("#showroom").animate({
left: "+=980"
});
}
});
回答2:
$("body").keydown(function(e){
// left arrow
if ((e.keyCode || e.which) == 37)
{
// do something
}
// right arrow
if ((e.keyCode || e.which) == 39)
{
// do something
}
});
回答3:
This works fine for me :
$(document).keypress(function (e){
if(e.keyCode == 37) // left arrow
{
// your action here, for example
$('#buttonPrevious').click();
}
else if(e.keyCode == 39) // right arrow
{
// your action here, for example
$('#buttonNext').click();
}
});
回答4:
I prefer using this template:
$(document).keypress(function(e){
switch((e.keyCode ? e.keyCode : e.which)){
//case 13: // Enter
//case 27: // Esc
//case 32: // Space
case 37: // Left Arrow
$("#showroom").animate({left: "+=980"});
break;
//case 38: // Up Arrow
case 39: // Right Arrow
$("#showroom").animate({left: "-=980"});
break;
//case 40: // Down Arrow
}
});
回答5:
The use of named functions expression may help to keep a cleaner code :
function go_left(){console.log('left');}
function go_up(){console.log('up');}
function go_right(){console.log('right');}
function go_down(){console.log('down');}
$(document).on('keydown',function(e){
var act={37:go_left, 38:go_up, 39:go_right, 40:go_down};
if(act[e.which]) var a=new act[e.which];
});
来源:https://stackoverflow.com/questions/4104158/jquery-keypress-left-right-navigation