在Firefox中慢慢突出显示 [英] Slow highlighting in Firefox

查看:84
本文介绍了在Firefox中慢慢突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要在html页面中为某些关键字/句子添加锚点和突出显示。事实证明,Firefox中的突出显示速度非常慢。

We need to add anchors and highlights for some keywords/sentences in the html page. It turns out the highlighting is really slow in Firefox.

在以下代码中,需要突出显示的所有范围都存储在数组 hiliteRanges

In the following code, all ranges which need to be highlighted are stored in array hiliteRanges:

for (var i = 0; i < hiliteRanges.length; i++){
    document.designMode = "on";

    var selHilites = window.getSelection();

    if (selHilites.rangeCount > 0)
        selHilites.removeAllRanges();

    selHilites.addRange(hiliteRanges[i]);

    var anchorId = 'index'+i;
    var insertedHTML = '<span id="' + anchorId + '" style="background-color: #FF8C00;" >'+hiliteRanges[i].toString()+'</span>';

    document.execCommand('inserthtml', false, insertedHTML);                                                                                    
    document.designMode = "off";
}

有没有办法加快处理速度?我们可以在数组中有数百个范围 hiliteRanges 。我们曾尝试在循环外部移动 designMode 设置,但是当循环运行时,我们可以看到html页面中的某些部分是可编辑的。

Is there any way to speed up the processing? We could have hundreds of ranges in the array hiliteRanges. We once tried moving the designMode setting outside of the loop, but we can see some sections are editable in the html page when the loop is running.

推荐答案

为此,无需使用 document.execCommand()。只需使用范围方法,然后就不需要 designMode

There's no need to use document.execCommand() for this. Just use range methods instead, and then there's no need for designMode.

var anchorId, hiliteTextNode, hiliteSpan;
for (var i = 0; i < hiliteRanges.length; i++){
    // Create the highlight element
    hiliteSpan = document.createElement("span");
    hiliteSpan.id = anchorId;
    hiliteSpan.style.backgroundColor = "#FF8C00";

    hiliteTextNode = document.createTextNode(hiliteRanges[i].toString());
    hiliteSpan.appendChild(hiliteTextNode);

    // Replace the range content
    hiliteRanges[i].deleteContents();
    hiliteRanges[i].insertNode(hiliteSpan);
}

此外,由于范围受DOM变异影响,我建议做这部分在使用 window.find()收集范围的同时。以下是一个例子:

Also, since ranges are affected by DOM mutation, I would suggest doing this part at the same time as you collect the ranges with window.find(). Here's an example:

http://jsfiddle.net/YgFjT /

这篇关于在Firefox中慢慢突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆