[英]On selecting text from HTML paragraph using window.getSelection(), the range index value is giving 0 when text from different/child tag is selected
I am trying select text from a HTML paragraph and get the index range.我正在尝试 HTML 段落中的 select 文本并获取索引范围。
To get the range values, i'm using the below code要获取范围值,我使用以下代码
{
startIndex = window.getSelection().getRangeAt(0).startOffset;
endIndex = window.getSelection().getRangeAt(0).endOffset;
}
Below is the HTML paragraph.下面是 HTML 段。
<p>Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
Now when i select the word "habitant" the startOffset() is returning 0 as a new/child tag started but i need the index starting from the paragraph现在当我 select 单词“habitant”时 startOffset() 返回 0 作为新/子标签开始但我需要从段落开始的索引
It returns 0 because the work "habitant" is wrapped inside another node so the anchor node won't be the hall paragraph it'll be just the node <b>haitant</b>
you can either fix this by removing the tag <b>
.它返回 0 因为工作“居民”被包裹在另一个节点中,所以锚节点不会是大厅段落,它只是节点
<b>haitant</b>
你可以通过删除标签来解决这个问题<b>
。
<p class="text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
another workaround will be to search for the selected word inside the parent node另一种解决方法是在父节点内搜索选定的单词
<p class="text">Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
const getSelectedTextIndex = () => {
const selectedText = window.getSelection().toString()
startIndex = document.querySelector('.text').innerText.indexOf(selectedText)
endIndex = startIndex + selectedText.length
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.