gpt4 book ai didi

javascript - 使用 dispatchEvent 以编程方式将键发送到输入

转载 作者:行者123 更新时间:2023-11-29 16:41:20 25 4
gpt4 key购买 nike

我正在尝试根据用户操作将字符发送到输入元素。

我正在尝试将 KeyboardEventdispatchEvent 一起使用,但无论我做什么,它都不起作用

例如:

let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;

不确定这是否正确,但我已经发送如下:

  document.querySelector('input').dispatchEvent(keyEvent);
document.activeElement.dispatchEvent(keyEvent);
document.dispatchEvent(keyEvent);

DEMO

如果我在点击按钮之前先关注输入,什么都不会发生。有什么建议可能会出错吗?

最佳答案

实际上,出于安全原因,将 KeyboardEvent 分派(dispatch)到 input 元素不会生成您期望的操作。

KeyboardEvent文件说得很清楚:

Note: manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

所以 dispatchEvent 根本不起作用。

或者,考虑直接操作 input 元素。

关于javascript - 使用 dispatchEvent 以编程方式将键发送到输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45457875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com