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

前端 未结 12 1922
别那么骄傲
别那么骄傲 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:25

    For mouse events, I know that in Firefox at least the "shiftKey" property on the event object will tell you if the shift key is down. It's documented at MSDN but I haven't tried it in forever so I don't recall if IE does this right.

    Thus you should be able to check for "shiftKey" on the event object in your "click" handler.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-27 03:31

    This works great for me:

    function listenForShiftKey(e){
        var evt = e || window.event;
        if (evt.shiftKey) {
          shiftKeyDown = true;
        } else {
          shiftKeyDown = false;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:33
        $(document).on('keyup keydown', function(e){shifted = e.shiftKey} );
    
    0 讨论(0)
  • 2020-11-27 03:38

    The excellent JavaScript library KeyboardJS handles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.

    KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });
    

    If you want a simple version, head to the answer by @tonycoupland):

    var shiftHeld = false;
    $('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });
    
    0 讨论(0)
  • 2020-11-27 03:39

    For checking if the shiftkey is pressed while clicking with the mouse, there is an exact property in the click event object: shiftKey (and also for ctrl and alt and meta key): https://www.w3schools.com/jsref/event_shiftkey.asp

    So using jQuery:

    $('#anchor').on('click', function (e) {
        if (e.shiftKey) {
            // your code
        }
    });
    
    0 讨论(0)
提交回复
热议问题