简体   繁体   English

getSelection&surroundContents跨多个标签

[英]getSelection & surroundContents across multiple tags

I've got a script that changes the background colour of text that has been selected. 我有一个脚本可以更改已选择的文本的背景颜色。 However i'm encountering an issue when the text is selected across multiple elements/tags. 但是,当跨多个元素/标签选择文本时,我遇到了问题。

The code that i've got is: 我得到的代码是:

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

And the error being output is: 输出的错误是:

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

I believe this is to do with the getRange() function though i'm not too sure how to proceed since I am a beginner at javascript. 我相信这与getRange()函数有关,虽然我不太清楚如何继续,因为我是javascript的初学者。

Is there any other way I can replicate what I am trying to achieve? 有没有其他方法可以复制我想要实现的目标?

Many thanks. 非常感谢。

This question has been asked today: How can I highlight the text of the DOM Range object? 今天有人问过这个问题: 如何突出显示DOM Range对象的文本?

Here's my answer: 这是我的答案:

The following should do what you want. 以下应该做你想要的。 In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again. 在非IE浏览器中,它打开designMode,应用背景颜色,然后再次关闭designMode。

UPDATE UPDATE

Fixed to work in IE 9. 修复了在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);
    }
}

Well I think the use of mark.js library is great in this case. 我认为在这种情况下使用mark.js库非常棒。 The library's intention is to highlight all instances of a certain word in the HTML document, but it can be tweaked through the filter option function, and additional span attributes can be added through the each option function. 该库的目的是突出显示HTML文档中某个单词的所有实例,但可以通过过滤器选项功能进行调整,并且可以通过每个选项功能添加其他跨度属性。

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;
        }
  });
};

Check this JSFiddle sample for completed code that highlights user's selection, even across multiple HTML elements. 检查此JSFiddle示例以查找突出显示用户选择的已完成代码,甚至可以跨多个HTML元素。

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

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