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

标签 javascript html dom

我正在尝试找出如何获取在原始 HTML 上定义选择子字符串的索引。我知道当您选择文本时,可以使用 window.getSelectiondocument.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/

相关文章:

javascript - ajax更新后无法使用jquery选择表行id

JavaScript - 在全局变量中存储元素

javascript - 'a href' 按钮的单击功能未触发

javascript - 雅虎财经 Api 不返回值

javascript - 如何在ajax请求成功回调中获取自动parseJSON数据?

html - 为什么 'flex-grow' 在 Chrome 和 Firefox/Edge 中的行为不同?

html - 重复的 CSS3 横幅图像过渡

jquery - 在窗口底部 float 页面,同时保持相对位置 div

javascript - ng-click 表单外部未获取数据

javascript - DOM appendChild 备用