只需输入任何文字,例如一个“a”,console.log('newTextNode: ', newTextNode) 将返回“a”作为它的值(不在 Firefox 或 Stack Overflow 代码片段中)。
const para = document.querySelector('p')
let range = document.createRange()
// this won't automatically set the caret position in Firefox or Stack Overflow Code Snippet
range.setStart(para.firstChild, 1)
range.collapse()
window.getSelection().addRange(range)
document.addEventListener('keypress', (e) => {
// has this changed anything in Chromium?
range = window.getSelection().getRangeAt(0)
const newTextNode = document.createTextNode('hello')
// with Chromium, this simply returns the charater you just typed
console.log('newTextNode: ', newTextNode)
// in Edge/Chrome this changes the value of newTextNode
// in Firefox and Stack Overflow Code Snippet, this works as expected
range.insertNode(newTextNode)
})
<p contenteditable="true">text</p>