简体   繁体   中英

How can I pass two keydown events at the same time with JavaScript?

Is there a way using jQuery or vanilla JS that I can pass down 2 keystrokes?

Example: When I press the space key as an event listener, both the enter and shift key should get pressed and passed down together. I managed for the code to run, but for one single key stroke. Can someone shine some light on this?

$(document).keydown(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == 13) {

        document.addEventListener('keydown', function(ev) {
            console.log(ev.which);
        });

        var e = new KeyboardEvent('keydown', {
            'keyCode': 190,
            'which': 190
        });
        console.log(e);
        document.dispatchEvent(e);
    }
});

To add modifiers like shift , ctrl , or alt to a KeyPress event, you can pass those properties in the second constructor argument. See the documentation here .

// ex. Shift+Enter
var e = new KeyboardEvent("keydown", {
  key: "Enter",
  shiftKey: true,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM