我正在尝试找出如何获取在原始 HTML 上定义选择子字符串的索引。我知道当您选择文本时,可以使用 window.getSelection
或 document.selection
获取有关它的信息。但是,我无法将其用于我的目的。
这里是一个简单的例子,考虑以下 HTML:
<body><div>selected text</div></body>
如果我选择文本 selected text
,我想获取 [12, 24]
对,它定义了页面原始 HTML 上的选择范围.
最佳答案
搜索选定的元素。将标志添加到父元素。拿数据。 设置它们并移除标志。在控制台上显示结果。
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);
关于javascript - 使用 JavaScript 在原始 HTML 上查找选择范围索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40865943/