如何以编程方式模拟在可内容编辑的 HTML 元素中键入内容?

Pen*_*uin 5 html javascript contenteditable keyboard-events dom-events

我需要模拟用户以编程方式键入 HTML 元素的交互contenteditable

我不能使用诸如HTMLElement.onkeypress()或 之类的东西HTMLElement.fire()

element.innerHTML我无法使用或修改元素的实际代码或内容element.textContent,我需要一种方法来模拟它。

Dan*_*ger 6

Document.execCommand()您可以与insertText 命令一起使用,它也会自动触发input事件

const editor = document.getElementById('editor');

editor.oninput = (e) => console.log('Input');

setTimeout(() => {
  editor.focus();
  
  document.execCommand('insertText', false, 'Inserted text...\n\n');
}, 1000);
Run Code Online (Sandbox Code Playgroud)
body {
  display: flex;
  flex-direction: column;
  font-family: monospace;
}

#editor {
  box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125);
  border-radius: 2px;
  min-height: 64px;
  padding: 16px;
  outline: none;
}
Run Code Online (Sandbox Code Playgroud)
<div id="editor" contenteditable="true"></div>
Run Code Online (Sandbox Code Playgroud)

但是,请注意,它目前已过时,甚至在它在不同浏览器之间不一致之前(与 相同contenteditable):

过时的

此功能已过时。尽管它在某些浏览器中仍然可以工作,但不鼓励使用它,因为它可能随时被删除。尽量避免使用它。