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

时间:2014-02-17 15:17:36

标签: javascript html contenteditable

我需要保存并恢复插入符号位置,因为用户键入了一个可信的div(编写的html被编辑并在按下每个键时重新插入)。

我已经阅读并成功地将Tim Down用于解决类似问题的解决方案:https://stackoverflow.com/a/13950376/2086428

当插入符号位于空行时会发生问题,它将恢复到之前的非空行(尝试here,添加新行并保存/恢复光标)。

在解决方案的评论部分提出一个用户遇到了同样的问题,解决方案的作者暗示将<br>转换为字符。

我该怎么做? 有没有更简单的解决方案?

PS:我不能在这个项目中使用rangy。

2 个答案:

答案 0 :(得分:0)

你可以听keydown;每按一次Enter键,检查插入位置后是否有相同(或下一个兄弟)文本节点中的某些字符(您将在该行断开之前收到事件)。如果不在插入位置后添加,则保存位置。

其中一些实用程序非常有用:

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

答案 1 :(得分:0)

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/