【问题标题】:How can I save and restore Selection range in javascript?如何在 javascript 中保存和恢复选择范围?
【发布时间】:2017-01-26 18:08:44
【问题描述】:

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

用户路径

  1. 用户选中部分文字,点击保存
  2. 关闭内置的移动浏览器
  3. 打开内置的移动浏览器并查看恢复的选择。

我的想法是首先通过调用window.getSelection().getRangeAt(0) 获取范围,然后保存其startContainerendContainer 属性。检查以下演示 sn-p:

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));

}
#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;
}
    <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 属性正常。我需要保存哪些值才能在以后的会话中恢复选择范围?常见的实现方式有哪些?

参考: Range class, Selection class

【问题讨论】:

    标签: javascript html range selection


    【解决方案1】:

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

    var highlightRange = window.getSelection().getRangeAt(0);
    var serializedRange = rangy.serializeRange(highlightRange);
    var deseriazedRange = rangy.deserializeRange(serializedRange);
    

    重要提示: Rangy 库创建自己的RangyRange 类以便跨平台(我猜),如果你想使用DOM Range 类中的方法,其中一些不会可用,直到您将 rangy 设置为使用 Native Range

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多