我有 contenteditable
div
。每次更改 div 的内容时,都会调用用 span
(对于 CSS)包装每个单词的函数。我有两个问题:
- 设置
innerHTML
后,光标出现在div的开头,我希望光标停留在同一个位置, - 删除换行符。
我试图找到一个光标定位解决方案(例如 here ),但我无法用 Range
或 Selection
解决问题。这是 fiddle .
const div = document.querySelector('div')
div.addEventListener('input', () => {
let text = div.textContent
text = '<span>' + text.replace(/ /g, '</span> <span>').replace(/\n/g, '</span><br /><span>') + '</span>'
div.innerHTML = text
})
body {
background-color: white;
}
body > div {
background-color: black;
color: white;
font-family: Monospace;
padding: 0.5rem;
width: 20rem;
}
<div contenteditable="true">
Multiline text
<br />
Multiline
<br />
Text
</div>
最佳答案
下面的代码解决了您添加换行符代替换行符的问题的一部分。
问题在于使用 textContent
进行评估。让我们举个例子,假设你的 div
是用下面的内容初始化的:
<div contenteditable>
abc
<br/>
def
</div>
当有人第一次触发对该 div 的更改时,textContent
方法将返回
abc def
因为有关具有断点的内容的信息已经丢失,您会看到新行被删除。解决方案是改为将其更改为 innerHTML
,这样您就可以毫无损失地操作内容。
const div = document.querySelector('div')
div.addEventListener('input', () => {
let text = div.innerHTML
text = '<span>' + text.replace(/ /g, '</span> <span>').replace(/\n/g, '</span><br/><span>') + '</span>'
//console.log(text)
div.innerHTML = text
})
body {
background-color: white;
}
body > div {
background-color: black;
color: white;
font-family: Monospace;
padding: 0.5rem;
width: 20rem;
}
<div contenteditable="true">
Multiline text
<br />
Multiline
<br />
Text
</div>
对于问题的第二部分,你可以引用SO上类似问题的答案: How to set caret(cursor) position in contenteditable element (div)?
关于javascript - 在 contenteditable div 中用 span 包裹每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55557482/