繁体   English   中英

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

[英]Highlighting text in document (JavaScript) Efficiently

如何(有效地-不降低计算机[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查找指定的文本,更改(插入带有背景色的跨度)“ cloned”字符串,并将“ real”主体替换为“ cloned”字符串。
我只是认为这没有效率。
你还有其他建议吗? (很有创意:))

我已将我的答案中的以下内容改编为关于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>

使用这种结合这个 ,你应该是相当好的。 (这比尝试自己实现选择/选择突出显示逻辑要好得多。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM