Javascript jQuery按键左/右导航

Javascript jQuery按键左/右导航,javascript,jquery,keyboard,keypress,onkeypress,Javascript,Jquery,Keyboard,Keypress,Onkeypress,我想让我的内容滑块能够响应按键(左箭头键和右箭头键)功能。我读过一些关于几种浏览器和操作系统之间的冲突 用户可以在全球网站(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 我需要一个没有任何交叉(浏览器、

我想让我的内容滑块能够响应按键(左箭头键和右箭头键)功能。我读过一些关于几种浏览器和操作系统之间的冲突

用户可以在全球网站(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

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

这对我来说很好:

$("body").keydown(function(e) {
  if(e.keyCode == 37) { // left
    $("#showroom").animate({
      left: "-=980"
    });
  }
  else if(e.keyCode == 39) { // right
    $("#showroom").animate({
      left: "+=980"
    });
  }
});
$(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();
    }
});

我更喜欢使用此模板:

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

使用命名函数表达式可能有助于保持代码更清晰:

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];

});

我们现在在jQuery中不应该使用
which
而不是
keyCode
吗?我不知道,但是看看上面的演示,使用了e.keyCode。是的,你应该使用.which()来获取keyCode。例外情况是,如果您试图在任何规范化之前获取原始文本输入(我想这意味着检测到£key而不仅仅是£character),那么如果我没有弄错的话,最好使用on('keydown'而不是'keydown'。如果我们使用“which”就足够了,如果我们在纯Jquery世界中使用“which”
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];

});