jQuery键盘按键左/右导航

41

我希望我的内容滑块能够响应键盘左右箭头按键的功能。我已经了解到某些浏览器和操作系统之间可能存在一些冲突。

用户可以在全局网站(body)上进行内容导航。

伪代码:

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

我需要一个没有任何交叉浏览器和操作系统冲突的解决方案。

5个回答

96
$("body").keydown(function(e) {
  if(e.keyCode == 37) { // left
    $("#showroom").animate({
      left: "-=980"
    });
  }
  else if(e.keyCode == 39) { // right
    $("#showroom").animate({
      left: "+=980"
    });
  }
});

7
现在使用jQuery时,我们应该使用“which”而不是“keyCode”吗? - Shikiryu
我不知道,但是请看 http://api.jquery.com/keydown/ 上的演示。 在那里,使用了 e.keyCode。 - Flo Edelmann
是的,你应该使用 .which() 来获取按键码。例外情况是如果你想在任何规范化之前获取原始文本输入(我猜这意味着像检测 £ 键而不仅仅是 £ 字符这样的东西)。 - carpii
如果我没记错的话,使用on('keydown')比直接使用'keydown'更好。 - Scalpweb

15
$("body").keydown(function(e){
    // left arrow
    if ((e.keyCode || e.which) == 37)
    {   
        // do something
    }
    // right arrow
    if ((e.keyCode || e.which) == 39)
    {
        // do something
    }   
});

如果我们使用 "which",那就足够了。 - GOK

6

对我来说这很好用:

$(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();
    }
});

1
如果我们在纯Jquery世界中使用"which" - GOK

1
使用命名函数表达式可以帮助保持更干净的代码:
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];

});

1

我更喜欢使用这个模板:

$(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
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接