jQuery按键左/右导航

Tom*_*kay 40 javascript keyboard jquery keypress onkeypress

我想让我的内容滑块能够响应按键(左箭头键和右箭头键)功能.我已经阅读了几个浏览器和操作系统之间的一些冲突.

用户可以在全球网站(正文)上浏览内容.

伪代码:

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
Run Code Online (Sandbox Code Playgroud)

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

Flo*_*ann 94

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

  • 我们现在不应该使用`which`代替`keyCode`和jQuery吗? (7认同)

小智 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
    }   
});
Run Code Online (Sandbox Code Playgroud)


Erw*_*wan 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();
    }
});
Run Code Online (Sandbox Code Playgroud)