12

我有一个脚本可以更改已选择文本的背景颜色。但是,当跨多个元素/标签选择文本时,我遇到了问题。

我得到的代码是:

var text = window.getSelection().getRangeAt(0);
var colour = document.createElement("hlight");
colour.style.backgroundColor = "Yellow";
text.surroundContents(colour);

输出的错误是:

Error: The boundary-points of a range does not meet specific requirements. =
NS_ERROR_DOM_RANGE_BAD_BOUNDARYPOINTS_ERR
Line: 7

我相信这与 getRange() 函数有关,尽管我不太确定如何进行,因为我是 javascript 的初学者。

有没有其他方法可以复制我想要实现的目标?

非常感谢。

4

2 回答 2

18

今天有人问了这个问题:如何高亮DOM Range对象的文本?

这是我的答案:

以下应该做你想要的。在非 IE 浏览器中,它打开 designMode,应用背景颜色,然后再次关闭 designMode。

更新

固定在 IE 9 中工作。

function makeEditableAndHighlight(colour) {
    sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}
于 2010-04-06T11:18:59.897 回答
2

好吧,我认为在这种情况下使用mark.js库很棒。该库的目的是突出显示 HTML 文档中某个单词的所有实例,但可以通过filter选项功能对其进行调整,并且可以通过each选项功能添加额外的 span 属性。

function markFunc(node, text, color) {
  var instance = new Mark(node);
    instance.mark(text, {
    "element": "span",
      "className": color,
      "acrossElements": true,
      "separateWordSearch": false,
      "accuracy": "partially",
      "diacritics": true,
      "ignoreJoiners": true,
    "each": function(element) {
            element.setAttribute("id", "sohayb");
            element.setAttribute("title", "sohayb_title");
       },
    "done":function(totalMarks) {
            window.getSelection().empty();//This only in Chrome
            console.log("total marks: " + totalMarks);
     },
      "filter": function(node, term, totalCounter, counter) {
        var res = false;
        if (counter == 0) {
            res = selectionRange.isPointInRange(node, selectionRange.startOffset);
        } else {
        res = selectionRange.isPointInRange(node, 1);
        }
        console.log("Counter: " + counter + ", startOffset: " + selectionRange.startOffset);
        return res;
        }
  });
};

检查此JSFiddle 示例以获取突出显示用户选择的完整代码,甚至跨多个 HTML 元素。

于 2017-02-08T07:01:40.833 回答