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

How to find index of selected text in getSelection() using javascript?

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

我试过使用"indexOf(...)"方法。但它 returns 第一次出现 selected 子字符串。我想要子字符串相对于原始字符串的实际位置。例如..,如果我 select 字母 'O' 在位置 3 [YOLO Cobe],我希望索引为 3 但 indexOf() 方法returns 1 这是 'O' 在 [YOLO Cobe] 中的第一次出现。

是否有任何其他方法获取 selected 文本的实际开始和结束索引而不是第一次出现?

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);
        }
});
<div id="ip">YOLO Cobe</div>

您要查找的内容在 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);
        }
});
<div id="ip">YOLO Cobe</div>

下面是基于@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)
});
<div><span>Fragment1</span> fragment2 <span>fragment3</span></div>

window.getSelection().anchorOffset 将为您提供所需的索引。

MDN link: https://developer.mozilla.org/en-US/docs/Web/API/Selection/anchorOffset

我尝试使用 getSelection() 方法中的 anchorOffsetfocusOffset,但它没有给我所需的索引。

所以我自己想出了这个解决方案(注意:它在 chrome 中有效,不知道其他浏览器)

HTML

<input type="text" class="input" hidden />
<textarea> remind me to be here to morrow </textarea>

JS

let text = document.querySelector("textarea");
let input = document.querySelector(".input");

在这种情况下,“here to morrow”是突出显示的部分。

我选择的文字

input.value = getSelection();
let selectedText = input.value;

对于所选文本的起始索引,我做了

let start = body.value.indexOf(getSelection());
let end = start + selectedText.lenght;

希望这有用