如何同时模拟多个按键事件

时间:2017-03-09 15:30:52

标签: javascript jquery

我发现了这种方式,但有了它,我只能在.which中设置一个键码,我想模拟键 ALT + space + x 同时。

ALT 我可以使用.altKey = true;

 $(".btn").click(function() {
    var e = jQuery.Event("keypress");
    e.which = 88;       // x code value
    e.altKey = true;     // Alt key pressed
    $("input").trigger(e);
 });

如何添加空格键码?

1 个答案:

答案 0 :(得分:0)

我为之前的回答道歉。我想过如何处理。现在我修改代码来处理和触发:

您可以使用两个事件来实现它:keyDown和keyUp,如下所示:

var x,
    alt,
    space;

document.addEventListener('keydown', function (e) {
    e = window.event ? event : e;
    switch (e.keyCode) {
        case 88:
            x = true;
            break;
        case 18:
            alt = true;
            break;
        case 32:
            space = true;
            break;
    }
});

document.addEventListener('keyup', function (e) {
    if (x && alt && space) {
        alert("alt + space + x Pressed!");
    }

    x = alt = space = false;
});

function triggerEvent(eventName, keyCode) {
    var event; // The custom event that will be created

    if (document.createEvent) {
        event = document.createEvent('HTMLEvents');
        event.initEvent(eventName, true, true);
    } else {
        event = document.createEventObject();
        event.eventType = eventName;
    }

    event.eventName = eventName;
    event.keyCode = keyCode || null;

    if (document.createEvent) {
        document.dispatchEvent(event);
    } else {
        document.fireEvent('on' + event.eventType, event);
    }
}

triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');

https://jsfiddle.net/m83omwq5/1/