我有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)?上提及类似问题的答案