在修改innerHTML之后,在contentEditable上保存/恢复选择 [英] Save / restore selection on contentEditable AFTER modifying innerHTML

查看:414
本文介绍了在修改innerHTML之后,在contentEditable上保存/恢复选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在contentEditable中获取/设置光标位置几乎是不可能的。我不在乎了解这些信息。我需要能够保存当前选择,修改div的innerHTML,然后恢复选择。

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.

我正在试验 contenteditable selected text save and restore 。它在输入div之后有效,但不能在 以编程方式 修改div的innerHTML之后。相反,当我调用restoreSelection时,插入符号只是开始。

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.

有关如何在修改innerHTML后如何在contentEditable上保存/恢复选择的任何建议非常感激。而不是打字。

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.

推荐答案

如果你在现有的<$ c $上进行某种字符串替换您可编辑元素的c> innerHTML ,您可以使用我的 Rangy 库及其保存/恢复选择模块。它使用具有特定ID的不可见元素来标记选择的开始和结束边界,因此如果您的 innerHTML 更改不包含这些元素,那么这将无效。

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.

另一种选择是纯粹基于元素的文本节点内的字符索引来完成它。我在这里写了一个天真的实现: https://stackoverflow.com/q/5596688/96100

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

这篇关于在修改innerHTML之后,在contentEditable上保存/恢复选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆