gpt4 book ai didi

javascript - JS - surroundContents 仅在文本上保留约 20% 的高亮尝试

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:27 27 4
gpt4 key购买 nike

我正在使用 mouseup 事件来触发一个函数,该函数突出显示文本并用跨度包围突出显示的文本(来自堆栈溢出的函数):

function highlightText(e) {

var t = window.getSelection().toString();
if (t) {
$("#mySpan").remove();
var range = window.getSelection().getRangeAt(0);
newNode = document.createElement("span");
newNode.id = 'mySpan';

range.surroundContents(newNode);

}
}

我遇到的主要问题是,只要包含 surroundContents,文本就会保持高亮,只有大约 20% 的高亮尝试(否则高亮会立即消失)。我尝试添加一个 setTimeout,而不是调用 1s 的 surroundContent。我也尝试删除 remove() 语句,但仍然没有用。

关于为什么会发生这种情况有什么想法吗?

最佳答案

我在 Android 上使用 Chromium 时遇到了同样的问题。在某些特定情况下,调用 range.surroundContents(newNode) 会导致页面重新加载等非常奇怪的行为。检查后the documentation of the function :

This method is nearly equivalent to newNode.appendChild(range.extractContents()); range.insertNode(newNode). After surrounding, the boundary points of the range include newNode.

所以显而易见的事情是应用另一种方式突出显示文本。我找到了 mark.js库完全按照我的要求做了,没有那种烦人的副作用。 (这里有一个 JSFiddle sample 显示了它是如何用来突出显示选择的)。不同之处在于库没有使用 range.surroundContents(newNode) 也没有使用 newNode.appendChild 而是 node.replaceChild

基于此,这是我遇到的问题的解决方案,我认为它也适用于您的情况。

function surroundRangeWithSpan(range) {
var span = document.createElement('span');

// The text is within the same node (no other html elements inside of it)
if (range.startContainer.isEqualNode(range.endContainer) && range.startContainer.childNodes.length == 0) {
// Here you customise your <span> element
customSurroundContents(range, span);
} else {
// Here you have to break the selection down
}
return span;
}

function customSurroundContents(range, span) {
var node = range.commonAncestorContainer;
var startNode = node.splitText(range.startOffset);
var ret = startNode.splitText(range.toString().length);
span.textContent = startNode.textContent;
startNode.parentNode.replaceChild(span, startNode);
}

然后将 window.getSelection().getRangeAt(0) 传递给函数。

关于javascript - JS - surroundContents 仅在文本上保留约 20% 的高亮尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37471440/

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