简体   繁体   English

更改可编辑div元素的html结构时,如何恢复选择/插入符号位置?

[英]How to restore the selection / caret position when the html structure of an editable div element is changed?

I wrote a simple test to change the text in an editable div's content. 我编写了一个简单的测试,以更改可编辑div内容中的文本。 The html structure is changed but the text is the same. html结构已更改,但文本相同。

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head> 
    <title>Hello</title> 
    <script type="text/javascript" src="rangy-core.js"></script> 
    <script type="text/javascript" src="rangy- 
selectionsaverestore.js"></script> 
</head> 
<body>

<div id="show" class="code" contenteditable="true"><span 
style="color:red">12345</span>12345</div> 

<script type="text/javascript">

window.setTimeout(function () { 
    // save selection / caret position
    var show = document.getElementById("show"); 
    show.innerHTML = "1234512345"; 
    // restore select / caret position
}, 5000) 

</script> 

</body> 
</html>

I've tried rangy like this: 我已经尝试过像这样的rangy

var s = rangy.saveSelection(); 
var show = document.getElementById("show"); 
show.innerHTML = "1234512345"; 
rangy.restoreSelection(s); 

But it report an error: 但它报告一个错误:

Rangy warning: Module SaveRestore: Marker element has been removed. 严重警告:模块SaveRestore:标记元素已被删除。 Cannot restore selection. 无法还原选择。

Does rangy support the feature I mentioned above? rangy是否支持我上面提到的功能? If yes, how should I use it? 如果可以,该如何使用? If no, what should I do to implement that? 如果没有,我应该怎么做呢?

UPDATE: In my scenario I have to replace all the innerHTML since the text would be formatted into a very rich style. 更新:在我的场景中,我必须替换所有innerHTML,因为文本将被格式化为非常丰富的样式。 But in my case the text is always the same without the styles. 但就我而言,没有样式的文本总是一样的。 Is that any possible way to record the selection and caret position and set it back? 有什么可能的方法来记录选择和插入符号的位置并将其重新设置? What kind of API I should use? 我应该使用哪种API?

The error message is pretty descriptive of the problem, which is that Rangy's save/restore module uses hidden elements with specific IDs to mark the start and end of the selection range, meaning that if these elements are removed, the whole thing falls down. 错误消息很好地说明了问题,这是Rangy的保存/恢复模块使用具有特定ID的隐藏元素来标记选择范围的开始和结束,这意味着如果删除了这些元素,整个过程就会崩溃。

The obvious solution is to store the selection as character positions within the visible text. 显而易见的解决方案是将所选内容存储为可见文本内的字符位置。 This isn't as easy as it may appear, however. 但是,这并不像看起来那样容易。 I'm actively working on a module to do this properly and hope to release something in the next couple of months. 我正在积极研究一个模块,以正确地执行此操作,并希望在未来几个月内发布一些内容。 In the meantime, here's a naive solution that is good enough for many situations: 同时,这是一个天真的解决方案,足以应付许多情况:

replace innerHTML in contenteditable div 在contenteditable div中替换innerHTML

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

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