jQuery keypress left/right navigation [duplicate]

ぐ巨炮叔叔 提交于 2019-11-27 18:29:21
$("body").keydown(function(e) {
  if(e.keyCode == 37) { // left
    $("#showroom").animate({
      left: "-=980"
    });
  }
  else if(e.keyCode == 39) { // right
    $("#showroom").animate({
      left: "+=980"
    });
  }
});
$("body").keydown(function(e){
    // left arrow
    if ((e.keyCode || e.which) == 37)
    {   
        // do something
    }
    // right arrow
    if ((e.keyCode || e.which) == 39)
    {
        // do something
    }   
});

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

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

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

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!