将“Alt”键加入现有按键功能

时间:2016-01-21 15:02:54

标签: javascript jquery

我想将'Alt'键笔划添加到现有击键功能。我使用此函数来导航页面,但我想要做的是将“Alt”按键添加到所有现有函数中。

因此,我只希望用'Alt + A'按键来代替'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");
        });
    });
}

2 个答案:

答案 0 :(得分:1)

因此请检查事件数据中的alt键。如果按下,那就是真的。

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

答案 1 :(得分:1)

您可以像在altKey事件中使用keypress一样执行此操作。

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