2016-01-21 51 views
0

我想將「Alt」鍵擊添加到現有的擊鍵功能。我使用這個函數來導航頁面,但是我想要做的是將「Alt」擊鍵添加到所有現有的函數中。將「Alt」鍵添加到現有的擊鍵功能

因此,我不希望讓'a'這個單獨的按鍵工作,而只希望它能與'Alt + A'的按鍵一起工作,任何幫助或想法都會受到歡迎。

$(document).ready(function() 
{ 
    // hides all DIVs with the CLASS container 
    // and displays the one with the ID 'home' only 
    $(".container").css("display","none"); 
    $("#home").css("display","block"); 

    // makes the navigation work after all containers have bee hidden 
    showViaLink($("ul#navigation li a")); 

    // listens for any navigation keypress activity 
    $(document).keypress(function(e) 
    { 
     switch(e.which) 
     { 
      // user presses the "a" 
      case 97: showViaKeypress("#home"); 
         break; 

      // user presses the "s" key 
      case 115: showViaKeypress("#about"); 
         break; 

      // user presses the "d" key 
      case 100: showViaKeypress("#contact"); 
         break; 

      // user presses the "f" key 
      case 102: showViaKeypress("#awards"); 
         break; 

      // user presses the "g" key 
      case 103: showViaKeypress("#links"); 
     } 
    }); 
}); 

// shows a given element and hides all others 
function showViaKeypress(element_id) 
{ 
    $(".container").css("display","none"); 
    // if multiple keys are pressed rapidly this will hide all but the last pressed key's div 
    $(".container").hide(1); 
    $(element_id).slideDown("slow"); 
} 

// shows proper DIV depending on link 'href' 
function showViaLink(array) 
{ 
    array.each(function(i) 
    { 
     $(this).click(function() 
     { 
      var target = $(this).attr("href"); 
      $(".container").css("display","none"); 
      $(target).slideDown("slow"); 
     }); 
    }); 
} 

回答

1

你可以像在你keypress事件像下面使用altKey以下。

$(document).keypress(function(e) { 
    if(e.altKey) { 
     switch(e.which) 
     { 
     // user presses the "a" 
     case 97: showViaKeypress("#home"); 
        break; 

     // user presses the "s" key 
     case 115: showViaKeypress("#about"); 
        break; 

     // user presses the "d" key 
     case 100: showViaKeypress("#contact"); 
        break; 

     // user presses the "f" key 
     case 102: showViaKeypress("#awards"); 
        break; 

     // user presses the "g" key 
     case 103: showViaKeypress("#links"); 
     } 
    } 
}); 
+0

阿齊姆似乎在演示突破:http://motorcyclecredit.com/test.htm – Blnukem

+0

我創建了這個工作小提琴:https://jsfiddle.net/azim101/dkk6twsc/。您需要在'keypress'事件中添加'e.preventDefault()'。 @ user1703803 – Azim

+0

好吧我弄清楚它在Firefox中工作的問題,但不是在Chrome中我使用的是Chrome – Blnukem

1

因此,請檢查事件Data中的alt鍵。如果按下,這將是真實的。

$(document).keypress(function(e){ 
    if (!e.altKey) return; 
    /* rest of code */ 
});