简体   繁体   English

Contenteditable div:当位于空的新行时保存和恢复插入位置

[英]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). 我需要保存并恢复插入符号位置,因为用户键入了一个可信的div(编写的html被编辑并在按下每个键时重新插入)。

I've read and succesfully used this solution by Tim Down to a similar question: https://stackoverflow.com/a/13950376/2086428 . 我已阅读并成功使用Tim Down的解决方案来解决类似的问题: 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. 在解决方案的评论部分提出一个用户有同样的问题,解决方案的作者暗示将<br>转换为字符。

How can I do this? 我怎样才能做到这一点? Are there any simpler solutions? 有没有更简单的解决方案?

PS: I can't use rangy for this project. PS:我不能在这个项目中使用rangy。

From this answer : 这个答案

The solution is to make sure, that every "br" tag is followed by a newline character (\\n). 解决方案是确保每个“br”标记后跟一个换行符(\\ 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. 这不会以任何可见的方式损害HTML内容,但是现在,只要调用range.toString(),所有HTML中断都会转换为纯文本换行符。

<br>\n

Working example here: http://jsfiddle.net/gEhjZ/95/ 这里的工作示例: http//jsfiddle.net/gEhjZ/95/

For comparison, example, which has problem (without \\n after "br"): http://jsfiddle.net/gEhjZ/94/ 比较,例如,有问题(没有\\ n在“br”之后): http//jsfiddle.net/gEhjZ/94/

You can listen to keydown; 你可以听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). 每按一次Enter键,检查插入位置后是否有相同(或下一个兄弟)文本节点中的某些字符(您将在该行断开之前收到事件)。 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 https://github.com/MailOnline/milo/blob/master/lib/util/dom.js https://github.com/MailOnline/milo/blob/master/lib/util/selection/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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