Mouse click simulates keyboard key in JavaScript

和自甴很熟 提交于 2019-12-25 02:41:21

问题


I have situation that in application (HTML/XUL) there are key bindings for some function keys (F5, F7 & F9) in order to communicate with some other application.

Now I have to make touch-based interface for same app, without keyboard and advanced touch events. All touch clicks are actually same as mouse clicks and I need to have 3 buttons/links that behave same as F5, F7 & F9 keys.

Don't ask for reasons, all I can say is that I need to keep that key bindings.

Can I assign mouse click on link to act like F-key is pressed?


回答1:


In Jake's answer is most of solution and based on that I gave the whole answer, because is not so easy on first glance for beginners to modify functionality. This is modified function from this thread:

function simulateKeyPress(target, options) {
    var event = target.ownerDocument.createEvent('KeyEvents'),
        options = options || {};

    // Set your options or || default values
    var opts = {
        type: options.type                  || "keypress",
        bubbles: options.bubbles            || true,
        cancelable: options.cancelable      || true,
        viewArg: options.viewArg            || null,
        ctrlKeyArg: options.ctrlKeyArg      || false,
        altKeyArg: options.altKeyArg        || false,
        shiftKeyArg: options.shiftKeyArg    || false,
        metaKeyArg: options.metaKeyArg      || false,
        keyCodeArg: options.keyCodeArg      || 0,
        charCodeArg: options.charCodeArg    || 0
    }

    // Pass in the options
    event.initKeyEvent(
        opts.type,
        opts.bubbles,
        opts.cancelable,
        opts.viewArg,
        opts.ctrlKeyArg,
        opts.altKeyArg,
        opts.shiftKeyArg,
        opts.metaKeyArg,
        opts.keyCodeArg,
        opts.charCodeArg
    );

    // Fire the event
    target.dispatchEvent(event);
    event.stopPropagation;
}

And now we call it on desired element/event for desired key to be pressed. Second argument is object with all options changeable (in my case keyCodeArg: 116 is only needed to be send to simulate F5 key press).

document.getElementById(element).addEventListener('click', function() {
    simulateKeyPress(this, {keyCodeArg: 116});
});

Mozilla Developer Network has nice articles about KeyboardEvents and initKeyEvent.




回答2:


There are two ways to do this I guess.

The simple way would be to have your F-keys call a function, and simply call the same function when catching a mouse event.

The other way would be to catch the mouse event, and fire a F-key press event. Then it would pretty much be a duplicate of this question:

How to simulate a mouse click using JavaScript?



来源:https://stackoverflow.com/questions/21303965/mouse-click-simulates-keyboard-key-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!