简体   繁体   中英

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. I then replace the matches with <span> elements and apply some styles to those span elements. Then I replace the complete text in the divider with the new text using the .innerHTML attribute. This works just fine, but I have to type backwards, because upon inserting the text, my cursor is reset to position zero. I tried recording the value of selectionStart before inserting and then doing

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? How do I manage to keep the cursor where it was?

element.selectionStart works for input elements, not for contentEditable elements. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM