如何通过Javascript获取句子中选中的字符串offset start和offset end
How to get the selected string offset start and offset end in the sentence by Javascript
我有两份,一份是下面的HTML版本
<div class="data-sentence" onclick="setSentenceNo(28);">
<p>
Statement of Advice for <span class="artemis_soa ano-subject" data-oristr="Joe" data-replaceid="tag_replace_6" data-hasqtip="7"><NAME_1></span> and <span class="artemis_soa ano-subject" data-oristr="Black" data-replaceid="tag_replace_3" data-hasqtip="8"><NAME_2></span>,
</p>
</div>
另一种是纯文本,如下所示。(也可以说是用户在浏览器中可以看到的内容)。
Statement of Advice for <NAME_1> and <NAME_2>,
所以我想要的是允许用户 select 字符串和 return 返回字符串用户 selected 的偏移量开始和偏移量结束。 (另外,我们不应该允许用户 select 保留标签,如 )。
例如用户select字符串'Advice',offset_start=13和offset_end=19
非常感谢你的帮助。
使用 window.getSelection()
and then Selection
and Range
API 获取您需要的偏移量。
document.body.onmouseup = function () {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
console.log(range.startOffset, range.endOffset);
};
<div><p>Statement of Advice for <span><NAME_1></span> and <span><NAME_2></span>,</p></div>
我有两份,一份是下面的HTML版本
<div class="data-sentence" onclick="setSentenceNo(28);">
<p>
Statement of Advice for <span class="artemis_soa ano-subject" data-oristr="Joe" data-replaceid="tag_replace_6" data-hasqtip="7"><NAME_1></span> and <span class="artemis_soa ano-subject" data-oristr="Black" data-replaceid="tag_replace_3" data-hasqtip="8"><NAME_2></span>,
</p>
</div>
另一种是纯文本,如下所示。(也可以说是用户在浏览器中可以看到的内容)。
Statement of Advice for <NAME_1> and <NAME_2>,
所以我想要的是允许用户 select 字符串和 return 返回字符串用户 selected 的偏移量开始和偏移量结束。 (另外,我们不应该允许用户 select 保留标签,如 )。
例如用户select字符串'Advice',offset_start=13和offset_end=19
非常感谢你的帮助。
使用 window.getSelection()
and then Selection
and Range
API 获取您需要的偏移量。
document.body.onmouseup = function () {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
console.log(range.startOffset, range.endOffset);
};
<div><p>Statement of Advice for <span><NAME_1></span> and <span><NAME_2></span>,</p></div>