我正在尝试将样式应用于用户选择的文本(鼠标拖动),我需要为其获取所选文本的开始和结束索引。
我尝试过使用“indexOf(...)”方法。但它返回所选子字符串的第一次出现。我想要子字符串相对于原始字符串的实际位置。例如..,如果我在位置 3 [YOL 选择字母“O” O Cobe],我希望索引为 3,但 indexOf() 方法返回 1,这是 [Y 中“O”的第一次出现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);
}
});
<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>
关于javascript - 如何使用 javascript 在 getSelection() 中查找所选文本的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56574059/