使用JavaScript在原始HTML上查找选择范围索引

时间:2016-11-29 12:28:51

标签: javascript html dom

我试图找出如何获取在原始HTML上定义选择子字符串的索引。我知道,当您选择文字时,可以使用window.getSelectiondocument.selection获取有关该文字的信息。但是,我无法将其用于我的目的。

这是一个简单的例子,请考虑以下HTML:

<body><div>selected text</div></body>

如果我选择文字selected text,我希望得到一对[12, 24],用于定义页面原始HTML上的选择范围。

1 个答案:

答案 0 :(得分:0)

搜索所选元素。将标志添加到父元素。拿数据。 设置它们并删除标志。在控制台上显示结果。

var selObj    = window.getSelection(); // Get info from selected text
var selectionBind = selObj.extentNode.parentElement; // find the nearest container to bind the flag
var nameBinding = 'data_bind'; // Name of the flag that we want to find 
selectionBind.setAttribute(nameBinding,''); // Set the flag on that selected element
var text      = selObj.anchorNode.data; // Get text from selected text
var selRange  = selObj.getRangeAt(0);

var offsetEnd = selRange.endOffset; // How long selected text was

var selected  = text.substring(0, offsetEnd); // Prepare only the selected text

var body   = document.body // Take all the body

var string = body.outerHTML; // Set them to line of string

var selectedBegin = string.search(nameBinding); // Find the text you selected on that string begin offset

var selectedEnd   = selectedBegin + offsetEnd - 1; // Value of the end of that selected text
selectionBind.removeAttribute(nameBinding); // Remove the flag
var data = [selectedBegin,selectedEnd];
console.log(data);