简体   繁体   中英

Contenteditable div: save and restore caret position when is positioned in empty new line

I need to save and restore the caret position as the user types in a contenteditable div (the html written is edited and re-inserted with each key pressed).

I've read and succesfully used this solution by Tim Down to a similar question: https://stackoverflow.com/a/13950376/2086428 .

The problem occurs when the caret is positioned in an empty line, it will be restored to the previous non-empty line (try it here , add a new line and save / restore the cursor).

In the comments section of the solution proposed one user had the same problem, the author of the solution hinted to convert the <br> s into characters.

How can I do this? Are there any simpler solutions?

PS: I can't use rangy for this project.

From this answer :

The solution is to make sure, that every "br" tag is followed by a newline character (\\n).

This won't hurt the HTML content in any visible way, but now all HTML breaks are translated to plain text line breaks as soon as range.toString() is being called.

<br>\n

Working example here: http://jsfiddle.net/gEhjZ/95/

For comparison, example, which has problem (without \\n after "br"): http://jsfiddle.net/gEhjZ/94/

You can listen to keydown; every time Enter key is pressed check if there are some character(s) in the same (or next sibling) text node immediately after caret position (you will receive event before the line is broken). If not add after caret position and then save the position.

Some of these utilities can be useful:

https://github.com/MailOnline/milo/blob/master/lib/util/dom.js https://github.com/MailOnline/milo/blob/master/lib/util/selection/index.js

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