问题描述
我试图将样式应用于用户选择的文本(鼠标拖动),为此我需要获取所选文本的开始和结束索引.
I am trying to apply style to the text selected by the user(mouse drag) for which I need to get the start and end index of the selected text.
我尝试使用"indexOf(...)"方法.但它返回所选子字符串的第一个匹配项.我想要子字符串相对于原始字符串的实际位置.例如..,如果我在位置3 [YOL O Cobe]上选择字母'O',我期望索引为3,但indexOf()方法返回1,这是第一次出现'[Y O LO Cobe]中的O'.
I have tried using "indexOf(...)" method. but it returns the first occurrence of the selected substring. I want the actual position of the substring with respect to the original string. For example.., if I select the letter 'O' at position 3 [YOLO Cobe], I expect the index as 3 but the indexOf() method returns 1 which is the first occurrence of 'O' in [YOLO Cobe].
还有其他方法来获取所选文本的实际开始和结束索引,而不是第一次出现吗?
Is there any other method of getting the actual start and end index of selected text and not the first occurrence ?
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注释的页面上更复杂的选择的示例:
And here is example for more complex selections on page based on @Kaiido comment:
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在getSelection()中找到选定文本的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!