1

我如何(有效地 - 不减慢计算机 [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 找到指定的文本,更改(插入带有背景颜色的跨度)“克隆”字符串并用“克隆”替换“真实”正文.
我只是觉得效率不高。
你还有其他建议吗?(有创意:))

4

3 回答 3

5

我已经根据我对 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");
于 2012-05-16T12:28:25.950 回答
1
<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>
于 2012-05-16T12:33:15.663 回答
0

将此与结合使用,您应该没问题。(这几乎比自己尝试实现选择/选择高亮逻辑要好。)

于 2012-05-16T12:23:12.813 回答