是否可以使用 Javascript/JQuery 在 DOM 窗口上触发按键事件
是否可以在 javascript 中触发 DOMWindow 或 DOMDocument 上的按键事件?基本上,我正在创建一个浏览器扩展来与网站交互,并且它们具有执行特定操作的快捷键事件(类似于 GMail)。我找到了有关如何正确触发关键事件的其他帖子(Definitive way使用 jQuery 触发按键事件),但在将按键事件发送到文档/窗口时它们似乎不起作用。
到目前为止,我已经尝试过:
var evt = document.createEvent("KeyboardEvent");
evt.initKeyboardEvent("keydown", true, true, window, false, false, false, false, 0, "o".charCodeAt(0))
window.document.dispatchEvent(evt);
和 jQuery 实现:
$(document).trigger({ type: 'keydown', which: "0".charCodeAt(0) });
我还尝试连续执行“keydown”、“keypress”和“keyup”,但这也不起作用。
任何帮助将不胜感激!
提前致谢。
is it possible to trigger a key event on the DOMWindow or DOMDocument in javascript? Basically I am creating an browser extension to interact with a website and they have shortcut Key Events (similar to GMail) on performing specific actions. I have found other postings on how to properly trigger key events (Definitive way to trigger keypress events with jQuery) but they don't seem to work when sending the key events to the document/window.
So far I have tried:
var evt = document.createEvent("KeyboardEvent");
evt.initKeyboardEvent("keydown", true, true, window, false, false, false, false, 0, "o".charCodeAt(0))
window.document.dispatchEvent(evt);
and a jQuery implementation:
$(document).trigger({ type: 'keydown', which: "0".charCodeAt(0) });
I also tried doing "keydown", "keypress" and "keyup" in succession but that did not work either.
Any help would be greatly appreciated!
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道您可以在使用
trigger()
时传递额外的参数,但我不确定您是否可以覆盖event
对象的属性。您可以像这样传递数据:这将是
trigger()
代码:这是一个演示:http://jsfiddle.net/A7cEE/ (观察控制台的日志)
您提供的 stackoverflow 答案中的代码似乎工作正常:
捕获:
触发:
演示:http://jsfiddle.net/A7cEE/1/
请注意
.on()
是 jQuery 1.7 中的新功能,在本例中与.bind()
相同。I know you can pass extra arguments when using
trigger()
but I'm not sure you can overwrite properties of theevent
object. You can pass data like this though:And this would be the
trigger()
code:Here is a demo: http://jsfiddle.net/A7cEE/ (watch your console for the logs)
The code from the stackoverflow answer you provided seems to work fine:
To Capture:
To Trigger:
Demo: http://jsfiddle.net/A7cEE/1/
Note that
.on()
is new in jQuery 1.7 and is the same as.bind()
in this case.试试这个:
语法:
使用“initKeyEvent”而不是“initKeyboardEvent”。
Try this:
syntax:
Use "initKeyEvent" instead of "initKeyboardEvent".
祝你好运。
Good Luck.