Javascript jQuery 按键左/右导航

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4104158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:37:17  来源:igfitidea点击:

jQuery keypress left/right navigation

javascriptjquerykeyboardkeypressonkeypress

提问by Tomkay

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.

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

回答by Flo Edelmann

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

回答by Ji?í Mel?ák

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

回答by Erwan

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

回答by Jacob Smith

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

回答by Tom Ah

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

});