鼠标单击模拟JavaScript中的键盘键 [英] Mouse click simulates keyboard key in JavaScript

查看:121
本文介绍了鼠标单击模拟JavaScript中的键盘键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是在应用程序(HTML / XUL)中有一些功能键(F5,F7和F9)的键绑定,以便与其他一些应用程序通信。

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.

现在我必须为同一个应用程序制作基于触摸的界面,没有键盘和高级触摸事件。所有触摸点击实际上与鼠标点击相同,我需要有3个按钮/链接,其行为与F5,F7和F9键。

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.

我可以在链接上指定鼠标点击,就像按下F键一样吗?

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

推荐答案

在杰克的答案是最解决方案并基于此我给出了完整的答案,因为初学者一眼就不那么容易修改功能。
这是来自此主题的修改功能:

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;
}

现在我们在所需的元素/事件上调用它,以便按下所需的键。第二个参数是对象,所有选项都可以更改(在我的情况下,keyCodeArg:116只需要发送到模拟F5键按下)。

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有很好的文章关于 KeyboardEvents initKeyEvent

Mozilla Developer Network has nice articles about KeyboardEvents and initKeyEvent.

这篇关于鼠标单击模拟JavaScript中的键盘键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆