我正在尝试使用 JavaScript 在浏览器中模拟用户输入.Click 事件已成功创建和分派,但由于某些原因,键盘事件的类似代码似乎根本不起作用.
I'm trying to simulate user input in browser with JavaScript. Click events are created and dispatched successfully but for some reasons a similar code for keyboard events doesn't seem to work at all.
var event = document.createEvent("KeyboardEvent");event.initKeyEvent("keydown", true, true, window, false, false, false, false, 87, 0);document.getElementById("id").dispatchEvent(event);
这会返回 true,但相应的字符不会出现在输入中.我也尝试过 keypress 和 keyup 也不起作用(针对 FF 和 Chrome 进行了测试).浏览器是否出于某些安全原因禁止它,或者我做错了什么?有没有办法让它工作?
This returns true but the corresponding character doesn't appear in the input. I tried with keypress and keyup as well which don't work either (tested against FF and Chrome). Is it prohibited by browser for some security reasons or I'm doing something wrong? Is there a workaround to get it work?
事件调度正常,所有事件监听器都会触发,没有发生的事情是角色没有被输入".这是因为事件的起源不是来自正确的来源.这是一个安全功能".
The event dispatches fine and all the event listeners will fire, the thing that does not happen is the character does not get "typed". This is because the origin of the event is not from the correct source. It's a "security feature".
模拟输入结果文本的唯一方法是重新设置 值 或以其他方式显式更改节点的内容.
The only way to simulate typing with resulting text is by re-setting the value or otherwise explicitly changing the contents of the node.
这篇关于调度键盘事件在 JavaScript 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)