我计划开发一个网络应用程序。在应用程序的一部分中,用户从段落中选择文本,然后单击保存按钮。
例如,用户从以下文本中选择“apple”(以粗体显示):
An apple is the pomaceous fruit of the Malus domestica tree of the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans. Malus domestica tree is often simple called as an apple tree.
当用户单击保存按钮时,JS 应该将其作为键值对添加到对象中。该值应该是选定的文本(在本例中是苹果),而键应该是指示它是选定文本的哪个实例的内容。原因是“apple”再次作为给定段落中倒数第二个单词出现。
类似于:
var object = new Object();
var textString = window.getSelection().toString();
object.indicator = textString;
我想跟踪用户选择了“apple”的哪个实例(即所选文本)。 那么有可能保留下来吗?
接下来的步骤是存储此对象,以便当用户再次启动此页面或返回此处时,我们告诉他他已经选择了什么。
最佳答案
此示例没有获取选择的实例(第一个或第二个),但它确实获取了字符串内的偏移索引,这应该足够了。
<div id="content">An apple is the pomaceous fruit of the Malus domestica tree of the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans. Malus domestica tree is often simple called as an apple tree.</div>
<button onclick="saveSelection()">Save Selection</button>
<script>
function saveSelection() {
var selection = window.getSelection();
var selectedText = selection.toString();
var selectionInfo = {
offset: selection.anchorOffset,
length: selectedText.length,
text: selectedText
};
localStorage["lastSelection"] = JSON.stringify(selectionInfo);
}
window.onload = function () {
var selectionJSON = localStorage["lastSelection"];
if (selectionJSON) {
selection = JSON.parse(selectionJSON);
alert(JSON.stringify(selection) + "\n" + document.getElementById("content").innerText.substr(selection.offset, selection.length));
}
};
</script>
关于Javascript:如何查找在长段落中选择了特定文本的哪个实例(例如,在段落中多次出现的单词)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26312116/