有效地突出显示文档中的文本 (JavaScript)

Highlighting text in document (JavaScript) Efficiently

本文关键字:文本 JavaScript 显示 文档 有效地      更新时间:2023-09-26

如何(有效地 - 不减慢计算机 [cpu])突出显示页面的特定部分?

假设我的页面是这样的:

<html>
<head>
</head>
<body>
"My generic words would be selected here" !.
<script>
//highlight code here
var textToHighlight = 'selected here" !';
//what sould I write here?
</script>
</body>
</html>

我的想法是将所有主体"克隆"到一个变量中,并通过 indexOf 查找指定的文本,更改(插入带有背景色的跨度)"克隆"字符串,并将"真实"主体替换为"克隆"主体。
我只是认为它效率不高。
你还有其他想法吗?(要有创意:))

我根据我对 SO(示例)的几个类似问题的回答改编了以下内容。它被设计为可重复使用的,并且已被证明是这样。它遍历您指定的容器节点内的 DOM,在每个文本节点中搜索指定的文本,并使用 DOM 方法拆分文本节点,并将相关文本块括在样式化的 <span> 元素中。

演示:http://jsfiddle.net/HqjZa/

法典:

// Reusable generic function
function surroundInElement(el, regex, surrounderCreateFunc) {
    // script and style elements are left alone
    if (!/^(script|style)$/.test(el.tagName)) {
        var child = el.lastChild;
        while (child) {
            if (child.nodeType == 1) {
                surroundInElement(child, regex, surrounderCreateFunc);
            } else if (child.nodeType == 3) {
                surroundMatchingText(child, regex, surrounderCreateFunc);
            }
            child = child.previousSibling;
        }
    }
}
// Reusable generic function
function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
    var parent = textNode.parentNode;
    var result, surroundingNode, matchedTextNode, matchLength, matchedText;
    while ( textNode && (result = regex.exec(textNode.data)) ) {
        matchedTextNode = textNode.splitText(result.index);
        matchedText = result[0];
        matchLength = matchedText.length;
        textNode = (matchedTextNode.length > matchLength) ?
            matchedTextNode.splitText(matchLength) : null;
        surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
        parent.insertBefore(surroundingNode, matchedTextNode);
        parent.removeChild(matchedTextNode);
    }
}
// This function does the surrounding for every matched piece of text
// and can be customized  to do what you like
function createSpan(matchedTextNode) {
    var el = document.createElement("span");
    el.style.backgroundColor = "yellow";
    el.appendChild(matchedTextNode);
    return el;
}
// The main function
function wrapText(container, text) {
    surroundInElement(container, new RegExp(text, "g"), createSpan);
}
wrapText(document.body, "selected here");
<html>
<head>
</head>
<body>
<p id="myText">"My generic words would be selected here" !.</p>
<script>
//highlight code here
var textToHighlight = 'selected here" !';
var text = document.getElementById("myText").innerHTML
document.getElementById("myText").innerHTML = text.replace(textToHighlight, '<span style="color:red">'+textToHighlight+'</span>');
//what sould I write here?
</script>
</body>
</html>

将它这个结合使用,你应该没问题。(这几乎比尝试自己实现选择/选择突出显示逻辑要好。