我需要模拟用户输入 contenteditable
的交互。以编程方式的 HTML 元素。
我不能使用诸如 HTMLElement.onkeypress()
之类的东西或 HTMLElement.fire()
.
我无法使用 element.innerHTML
修改元素的实际代码或内容或 element.textContent
,我需要一种方法来模拟它。
最佳答案
您可以使用 Document.execCommand()
与 insertText
command , 这也会触发 input
events自动地:
const editor = document.getElementById('editor');
editor.oninput = (e) => console.log('Input');
setTimeout(() => {
editor.focus();
document.execCommand('insertText', false, 'Inserted text...\n\n');
}, 1000);
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;
}
<div id="editor" contenteditable="true"></div>
但是,请注意,它目前已过时,甚至在它在不同浏览器之间不一致之前(与
contenteditable
相同):Obsolete
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
关于javascript - 如何以编程方式模拟输入内容可编辑的 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61569861/