Save / restore selection on contentEditable AFTER modifying innerHTML

帅比萌擦擦* 提交于 2019-12-30 18:29:18

问题


I know getting / setting cursor position in a contentEditable is damn near impossible. I don't care about knowing this information. I need to be able to save current selection, modify innerHTML of the div, and then restore the selection.

I've bee experimenting with the answer provided at contenteditable selected text save and restore . It works after typing in the div, but not after programmatically modifying the innerHTML of the div. Instead, when I call restoreSelection, the caret simply goes to the beginning.

Any suggestions as to how to be able to save / restore selection on a contentEditable after modifying the innerHTML instead of typing would be much appreciated.


回答1:


If you're doing some kind of string substitution on the existing innerHTML of your editable element, you may be able to use my Rangy library and its save/restore selection module. It uses invisible elements with particular IDs to mark the start and end boundaries of the selection, so if your innerHTML change does not include these elements then this will not work.

Another alternative is to do it based purely on character indices within the text nodes of the element. I've written a naive implementation here: https://stackoverflow.com/q/5596688/96100



来源:https://stackoverflow.com/questions/8236427/save-restore-selection-on-contenteditable-after-modifying-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!