如何使用Javascript在Safari中生成按键事件? [英] How can I generate a keypress event in Safari with Javascript?
问题描述
如何以编程方式从Safari中运行的Javascript代码生成按键事件?看起来WebKit使用DOM 3级模型从Javascript创建键盘事件,而DOM 3级键盘事件模型不支持keypress事件。还有其他方法可以使用吗?
How can I programmatically generate keypress events from Javascript code running in Safari? It looks like WebKit is using the DOM level 3 model for creating keyboard events from Javascript, and the DOM level 3 keyboard event model does not support the keypress event. Is there another way that I can use?
我正在寻找尽可能纯粹的Safari / WebKit DOM解决方案。我真的不想修改网页,我也不想在外部库上添加依赖项。我需要激活任何现有的按键处理程序,因此无法添加新的处理程序并直接调用它。
I'm looking for as pure a Safari/WebKit DOM solution as possible. I'd really prefer not to modify the web page, and I'd also rather not add dependencies on external libraries. I need to activate any existing keypress handlers, so it won't work to add a new handler and directly call it.
看起来WebKit具有keyCode和charCode属性在其UIEvent类中定义的keypress事件,但它们是只读的。有没有办法设置这些属性?以下不起作用:
It looks like WebKit has the keyCode and charCode properties of the keypress event defined in its UIEvent class, but they are read-only. Is there any way to set those properties? The following does not work:
var evt = document.createEvent('UIEvents');
evt.initUIEvent('keypress', true, true, window, 0);
evt.keyCode = 114; // 'r'
evt.charCode = 114;
alert("keyCode = " + evt.keyCode + ", charCode = " + evt.charCode); // both 0
在调用initUIEvent时设置detail属性似乎也没有效果。
Setting the detail property in the call to initUIEvent also seems to have no effect.
推荐答案
使用TextEvent(由DOM3引入)。由于您正在寻找生成按键事件,我猜你正在使用角色。在下面的代码中,textToInsert是一个字符串,textarea是我将事件调度到的元素。
Use the TextEvent (introduced by DOM3). Since you're looking to generate keypress events, I'm guessing you're working with characters. In the code below, textToInsert is a string, and textarea the element I'm dispatching the event to.
var eventObject = document.createEvent('TextEvent');
eventObject.initTextEvent('textInput',
true,
true,
null,
textToInsert);
textarea.dispatchEvent(eventObject);
这适用于Safari 3.1.2(因此在Chrome上)。
This works on Safari 3.1.2 (consequently on Chrome).
这篇关于如何使用Javascript在Safari中生成按键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!