Detecting combination keypresses (Control, Alt, Shift)?

前端 未结 3 1482
一向
一向 2020-11-29 22:28

I am trying to make a script run when Ctrl + Alt + e is pressed.
How can Tampermonkey fire on a simultaneous ctrl, alt, and e key?

3条回答
  •  难免孤独
    2020-11-29 22:56

    The keypress event is fired as soon as a key has been pressed. If you are pressing multiple keys, it will fire the event for each press, so they are considered independent key presses.

    Instead, you can use both the keydown and keyup events to detect multiple key presses. You can have an object that contains the 3 keys and a boolean state. On the keydown event, if the current key matches a key in the object, you set the state to true for that key. On the keyup event, you reset the state for the current key to false. If all 3 states are true at the time of the last key press, then fire the event.

    See this example that achieves this logic using jQuery.

    Update Brock's answer is a better solution for you using modifier keys in combination with a single key code target, as the ctrlKey and altKey modifiers are detected in combination, not handled independently. If you want to detect multiple key codes like, E and F together, for example, you'd need to keep track of them using keydown and keyup as per above.

提交回复
热议问题