首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在javascript中保存和恢复选择范围?

如何在javascript中保存和恢复选择范围?
EN

Stack Overflow用户
提问于 2016-09-19 06:25:28
回答 1查看 2.6K关注 0票数 6

我希望保存(序列化) Selection范围,以便在我的UIWebView of iOS应用程序中的下一个用户会话中重用(反序列化)它。

用户路径

  1. 用户选择文本部分,单击“保存”。
  2. 关闭内置的移动浏览器。
  3. 打开内置的移动浏览器,并看到恢复的选择。

我的想法是首先通过调用window.getSelection().getRangeAt(0)获得范围,然后保存它的startContainerendContainer属性。请检查以下演示片段:

代码语言:javascript
运行
复制
function saveSelectedRange() {  
  var highlightRange = window.getSelection().getRangeAt(0);
  
  var range = document.createRange();
  // ???
  console.log("start container: " + JSON.stringify(highlightRange.startContainer));
  console.log("end container: " + JSON.stringify(highlightRange.endContainer));

}
代码语言:javascript
运行
复制
#intro {
    font-size: 125%;
    color: green;
}

p.small {
    font-size: 75%;
}

#content {
    margin-left: 330px;
}

#buttons {
    left: 10px;
    position: fixed;
    border: solid black 1px;
    background-color: background:#C0ED72;
    padding: 5px;
    width: 300px;
}

html.ie6 #buttons {
    position: absolute;
}

#buttons h3 {
    font-size: 125%;
    font-weight: bold;
    margin: 0;
    padding: 0.25em 0;
}
代码语言:javascript
运行
复制
    <div id="buttons">
        <h3>Save selection range</h3>
        <p>Make a selection in the document and use the button below to save the selection range </p>
        <input type="button" ontouchstart="saveSelectedRange();" onclick="saveSelectedRange();" value="Save selection range">

    </div>

    <div id="content">
        <h1>Demo</h1>
        <p id="intro">
            Please use your mouse to make selections from the sample content and use the button
            on the left to save the selection range.
        </p>
</div>

正如您所看到的,控制台记录空的startContainerendContainer值,但是startOffsetendOffset属性是可以的。需要保存哪些值才能在以后的会话中恢复选择范围?实现这一目标的共同途径是什么?

参考文献: 范围类选择类

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-19 08:24:43

通过使用@TimDown rangy-library和他的模块,我终于解决了这个问题。

代码语言:javascript
运行
复制
var highlightRange = window.getSelection().getRangeAt(0);
var serializedRange = rangy.serializeRange(highlightRange);
var deseriazedRange = rangy.deserializeRange(serializedRange);

重要注意: Rangy库创建自己的RangyRange类以实现跨平台(我猜),如果您想使用来自DOM Range类的方法,其中一些方法将不可用,直到您设置rangy以使用Native Range为止。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39566611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档