[英]preserve cursor position when changing innerHTML in a contenteditable div
I'm building an Editor that does syntax highlighting on code.我正在构建一个对代码进行语法高亮显示的编辑器。 My current approach is to just take the text in the editor (a div with contenteditable set to true) and check for regex matches in the string.我目前的方法是只在编辑器中获取文本(一个 contenteditable 设置为 true 的 div)并检查字符串中的正则表达式匹配。 I then replace the matches with <span>
elements and apply some styles to those span elements.然后我用<span>
元素替换匹配项并将一些 styles 应用于这些 span 元素。 Then I replace the complete text in the divider with the new text using the .innerHTML
attribute.然后,我使用.innerHTML
属性将分隔符中的完整文本替换为新文本。 This works just fine, but I have to type backwards, because upon inserting the text, my cursor is reset to position zero.这很好用,但我必须向后输入,因为在插入文本后,我的 cursor 被重置为 position 零。 I tried recording the value of selectionStart
before inserting and then doing我尝试在插入之前记录selectionStart
的值,然后执行
element.selectionStart = oldSelectionStart + 1;
but it didn't work.但它没有用。 I assume this is because of chrome's render pipeline, where JavaScript is run before rendering the page, and the cursor is reset upon render, not upon set... Can anyone help?我假设这是因为 chrome 的渲染管道,其中 JavaScript 在渲染页面之前运行,而 cursor 在渲染时重置,而不是在设置时重置......有人可以帮忙吗? How do I manage to keep the cursor where it was?我如何设法将 cursor 保留在原处?
element.selectionStart
works for input elements, not for contentEditable
elements. element.selectionStart
适用于输入元素,不适用于contentEditable
元素。 You should try creating a Range
object, set its startContainer
& startOffset
and collapse it to set caret at the required position. Refer to [https://developer.mozilla.org/en-US/docs/Web/API/Range] for details.您应该尝试创建一个Range
object,设置其startContainer
和startOffset
并将其折叠以将插入符设置为所需的 position。请参阅 [https://developer.mozilla.org/en-US/docs/Web/API/Range] 了解细节。
PS: If you would like to set your cursor to the 'end of line', you could do it easily with range.selectNode(requiredNode)
and range.collapse(true)
to move the caret to the end of node, ie, line PS:如果您想将 cursor 设置为“行尾”,您可以使用range.selectNode(requiredNode)
和range.collapse(true)
轻松完成,将插入符号移动到节点的末尾,即行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.