2010-11-05 85 views
35

我想給我的內容滑塊響應按鍵(左箭頭鍵和右箭頭鍵)功能的能力。我已閱讀了幾個瀏覽器和操作系統之間的一些衝突。jQuery按鍵左/右導航

用戶可以在全球網站(正文)上瀏覽內容。

僞代碼:

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 

我需要一個解決方案,無需任何交叉(瀏覽器,操作系統)的衝突。

回答

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

現在我們不應該使用'which'而不是'keyCode'來使用jQuery嗎? – Shikiryu 2010-11-05 08:51:09

+0

我不知道,但看http://api.jquery.com/keydown/ 演示在那裏,使用e.keyCode。 – elektronikLexikon 2010-11-05 09:03:35

+0

是的,你應該使用.which()來獲得鍵碼。例外是,如果你想在任何規範化之前獲得原始文本輸入(我猜這意味着像檢測英鎊鍵而不是簡單的英鎊字符) – carpii 2014-12-27 23:12:14

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

如果我們使用「which」它足夠了 – GOK 2012-07-27 12:26:46

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 2012-07-27 12:27:10

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

});