通过 JS 中的调度事件以编程方式输入输入

Type in input programmatically via dispatch event in JS

如何像键盘打字一样输入?我知道我们可以通过设置输入值来实现,但是我怎样才能真正模拟键盘输入?

这里是显示 keydown 但不输入任何内容的示例代码。

html代码:


<p>Info: <input id="info" style="width:50%"></p>
<p>show: <input id="show" style="width:50%"></p>
<p><button onclick="showType()">Type in show</button></p


js代码:

document.addEventListener("keydown", function(ev) {
  document.getElementById("info").value = 
    "key= "+ev.key+" : "+ev.code+" : "+ev.keyCode;
}, true);

function showType(){
  document.getElementById("show").focus()
  document.getElementById("show").dispatchEvent(
  new KeyboardEvent("keydown", {
    key: "d",
    code: "KeyD",
    keyCode: 68,
    shiftKey: false,
    ctrlKey: false,
    metaKey: false
  })
);
}

codepen link

基于 MDN 出于安全原因,不允许这样做。因此,您需要手动更新该值。

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.