JavaScript如何模拟按键事件改变文本内容和提交表单?

问题描述 投票:0回答:1

我想创建一个JavaScript函数,可以模拟keypress事件来更改div中的文本内容,然后使用按钮点击事件提交。

例如,假设我有一个ID为“

myDiv
”的div,我想将其内容更改为“Hello world!”然后使用 ID 为“
myButton
”的按钮提交。我如何使用 JavaScript 实现此目的?

我想模拟按键事件而不是直接使用

div.textContent
方法改变文本内容。具体来说,我想填写并提交一个表单,其中文本输入是一个 div 元素,其
contenteditable 
属性设置为
true
.

任何帮助将不胜感激。谢谢!

const tweetBox = document.querySelector("[data-testid='tweetTextarea_0']");
  tweetBox.focus();
  tweetBox.textContent = "";

  const text = "Hello, world!";
  for (const char of text) {
    const key = char.charCodeAt(0);
    console.log(key) ;
    const event = new KeyboardEvent("keypress", { keyCode: key });
    tweetBox.dispatchEvent(event);
  }

  const tweetButton = document.querySelector("[data-testid='tweetButtonInline']");
  tweetButton.click();

  console.log("\nButton Clicked");

div 里面的内容,没有被改变。

javascript dom event-handling keyboard-events inputsimulator
1个回答
0
投票

如果创建和调度事件,则

isTrusted
设置为
false
,而用户启动的事件将
isTrusted
设置为
false

这意味着键盘事件的默认事件处理程序不会被触发。然而,元素仍然接收事件,我们可以添加自己的事件处理程序来提供类似的功能。

onkeydown='if (!event.isTrusted) this.textContent+=event.key;'

首先判断动作是否是用户发起的,如果不是,则手动更改文本(如果不勾选

isTrusted
,用户输入的文本会加倍)。

function typeStr() {
  let str='hello world!';
  for (let ltr of str) {
    d=new KeyboardEvent("keydown", {key:ltr});
    out.dispatchEvent(d);
  }
}
<div id="out" style="border:black 2px solid" contenteditable
  onkeydown='if (!event.isTrusted) this.textContent+=event.key;'></div>
<button onclick="typeStr();">type</button>

© www.soinside.com 2019 - 2024. All rights reserved.