gpt4 book ai didi

javascript - window.getSelection() 忽略某些标签

转载 作者:行者123 更新时间:2023-11-28 07:55:32 28 4
gpt4 key购买 nike

下面是我的html代码:

<div id="text">This is <span class="ignore">some</span> short text.</div>

当我使用鼠标并从“is”到“short”进行选择时,使用下面在网上找到的函数,

function getSelectionCharOffsetsWithin(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != "undefined") {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != "undefined" &&
(sel = document.selection).type != "Control") {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint("EndToStart", range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end
};
}

我将得到开始范围 = 5,结束范围 = 20。但我希望范围计算忽略 <span class="ignore">这样我只得到开始范围 = 5 和结束范围 = 14。

在处理之前,我将文本复制到另一个虚拟 div,但似乎 window.getSelection() 只能获取原始文本,有专家知道如何忽略 <span class="ignore"> 中的文本吗?这样我就能得到准确的范围?

最佳答案

JSFIDDLE

<div class="content">
Vivamus <span>luctus</span> urna sed urna ultricies ac tempor dui sagittis.
</div>

$(".content").on("mouseup", function () {
var start = window.getSelection().baseOffset;
var end = window.getSelection().focusOffset;
if (start < end) {
var start = window.getSelection().baseOffset;
var end = window.getSelection().focusOffset;
} else {
var start = window.getSelection().focusOffset;
var end = window.getSelection().baseOffset;
}
alert(window.getSelection());
alert(start + ", " + end);
});

关于javascript - window.getSelection() 忽略某些标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26136326/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com