本文介绍了在JavaScript中触发键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript在Safari中模拟键盘事件。

I'm trying to simulate a keyboard event in Safari using JavaScript.

我试过这个:

var event = document.createEvent("KeyboardEvent");
event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0);

...还有:

var event = document.createEvent("UIEvents");
event.initUIEvent("keypress", true, true, window, 1);
event.keyCode = 115;

然而,尝试这两种方法后,我遇到了同样的问题:代码执行完毕后, keyCode / 事件对象的哪些属性设置为 0 ,而不是 115

After trying both approaches, however, I have the same problem: after the code has been executed, the keyCode/which properties of the event object are set to 0, not 115.

有谁知道如何在Safari中可靠地创建和发送键盘事件? (如果可能的话,我宁愿用普通的JavaScript实现它。)

Does anyone know how to reliably create and dispatch a keyboard event in Safari? (I'd prefer to achieve it in plain JavaScript if possible.)

推荐答案

我正在研究。在最新的浏览器中或使用此polyfill,您可以执行以下操作:

I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:

element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })

var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);

//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})

更新:

现在我的polyfill支持旧版属性keyCode,charCode和which

Now my polyfill supports legacy properties "keyCode", "charCode" and "which"

var e = new KeyboardEvent("keydown", {
    bubbles : true,
    cancelable : true,
    char : "Q",
    key : "q",
    shiftKey : true,
    keyCode : 81
});

示例

此外,这里是与我的polyfill分开的跨浏览器initKeyboardEvent:

Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)

Polyfill

Polyfill demo

这篇关于在JavaScript中触发键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 17:25