JQuery or [removed] How determine if shift key being pressed while clicking anchor tag hyperlink?

前端 未结 12 2053
别那么骄傲
别那么骄傲 2020-11-27 03:00

I have an anchor tag that calls a JavaScript function.

With or without JQuery how do I determine if the shift key is down while the link is clicked?

The foll

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 03:30

    I have used a method to test if any specific key is pressed by storing the currently pressed key codes in an array:

    var keysPressed = [],
        shiftCode = 16;
    
    $(document).on("keyup keydown", function(e) {
        switch(e.type) {
            case "keydown" :
                keysPressed.push(e.keyCode);
                break;
            case "keyup" :
                var idx = keysPressed.indexOf(e.keyCode);
                if (idx >= 0)
                    keysPressed.splice(idx, 1);
                break;
        }
    });
    
    $("a.shifty").on("click", function(e) {
        e.preventDefault();
        console.log("Shift Pressed: " + (isKeyPressed(shiftCode) ? "true" : "false"));
    });
    
    function isKeyPressed(code) {
        return keysPressed.indexOf(code) >= 0;
    }
    

    Here is the jsfiddle

提交回复
热议问题