最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Saverestore selection on contentEditable AFTER modifying innerHTML - Stack Overflow

matteradmin3PV0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:11 CommunityBot 11 silver badge asked Nov 23, 2011 at 1:55 user1022241user1022241
Add a ment  | 

1 Answer 1

Reset to default 3

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./q/5596688/96100

Post a comment

comment list (0)

  1. No comments so far