Saving and Restoring caret position for contentEditable div

后端 未结 3 1137
耶瑟儿~
耶瑟儿~ 2020-11-29 08:49

I have a contentEditable div, the innerHTML of which can be updated through AJAX while editing. The problem is that when you change the contents of

3条回答
  •  [愿得一人]
    2020-11-29 08:59

    Update: I've ported Rangy's code to a standalone Gist:

    https://gist.github.com/timdown/244ae2ea7302e26ba932a43cb0ca3908

    Original answer

    You could use Rangy, my cross-browser range and selection library. It has a selection save and restore module that seems well-suited to your needs.

    The approach is not complicated: it inserts marker elements at the beginning and end of each selected range and uses those marker elements to restore the range boundaries again later, which could be implemented without Rangy in not much code (and you could even adapt Rangy's own code). The main advantage of Rangy is support for IE <= 8.

提交回复
热议问题