如何使用javascript在getSelection()中查找所选文本的索引?

Kee*_*ekz 7 javascript dom substring indexof getselection

我正在尝试将样式应用于用户选择的文本(鼠标拖动),我需要获取所选文本的开始和结束索引。

我试过使用“indexOf(...)”方法。但它返回所选子字符串的第一次出现。我想要子字符串相对于原始字符串的实际位置。例如..,如果我在位置 3 [ YOL O Cobe]处选择字母“O” ,我希望索引为 3,但 indexOf() 方法返回 1,这是 [Y O LO ] 中第一次出现的“O”科比]。

有没有其他方法可以获取所选文本的实际开始和结束索引而不是第一次出现?

function getSelectionText()
{
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}
document.getElementById('ip').addEventListener('mouseup',function(e)
{
        var txt=this.innerText;
        console.log(txt);
        var selectedText = getSelectionText();
        console.log(selectedText);
        var start = txt.indexOf(selectedText);
        var end = start + selectedText.length;
        if (start >= 0 && end >= 0){
    	    console.log("start: " + start);
    	    console.log("end: " + end);
        }
});
Run Code Online (Sandbox Code Playgroud)
<div id="ip">YOLO Cobe</div>
Run Code Online (Sandbox Code Playgroud)

paw*_*ina 6

您正在寻找的内容在返回的对象中可用 window.getSelection()

document.getElementById('ip').addEventListener('mouseup',function(e)
{
        var txt = this.innerText;
        var selection = window.getSelection();
        var start = selection.anchorOffset;
        var end = selection.focusOffset;
        if (start >= 0 && end >= 0){
    	    console.log("start: " + start);
    	    console.log("end: " + end);
        }
});
Run Code Online (Sandbox Code Playgroud)
<div id="ip">YOLO Cobe</div>
Run Code Online (Sandbox Code Playgroud)

以下是基于@Kaiido 评论的页面上更复杂选择的示例:

document.addEventListener('mouseup',function(e)
{
        var txt = this.innerText;
        var selection = window.getSelection();
        var start = selection.anchorOffset;
        var end = selection.focusOffset;
        console.log('start at postion', start, 'in node', selection.anchorNode.wholeText)
        console.log('stop at position', end, 'in node', selection.focusNode.wholeText)
});
Run Code Online (Sandbox Code Playgroud)
<div><span>Fragment1</span> fragment2 <span>fragment3</span></div>
Run Code Online (Sandbox Code Playgroud)

  • baseOffset 是 Chrome 的一个怪癖。官方属性是“anchorOffset”。此外,您可能想指出这些是按选择顺序排序的(也就是说,如果您从右到左选择可能有 `start: 7 end: 2` 并且这些索引是相对于它们自己的 `[anchor/ focus]Node`。它们可能不是同一个节点。 (2认同)