我希望保存(序列化) Selection
范围,以便在我的UIWebView
of iOS应用程序中的下一个用户会话中重用(反序列化)它。
用户路径
我的想法是首先通过调用window.getSelection().getRangeAt(0)
获得范围,然后保存它的startContainer
、endContainer
属性。请检查以下演示片段:
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>
正如您所看到的,控制台记录空的startContainer
、endContainer
值,但是startOffset
、endOffset
属性是可以的。需要保存哪些值才能在以后的会话中恢复选择范围?实现这一目标的共同途径是什么?
发布于 2016-09-19 08:24:43
通过使用@TimDown rangy-library
和他的模块,我终于解决了这个问题。
var highlightRange = window.getSelection().getRangeAt(0);
var serializedRange = rangy.serializeRange(highlightRange);
var deseriazedRange = rangy.deserializeRange(serializedRange);
重要注意: Rangy库创建自己的RangyRange
类以实现跨平台(我猜),如果您想使用来自DOM Range
类的方法,其中一些方法将不可用,直到您设置rangy
以使用Native Range
为止。
https://stackoverflow.com/questions/39566611
复制相似问题