【问题标题】:getSelection & surroundContents across multiple tags跨多个标签的 getSelection 和环绕内容
【发布时间】:2023-03-11 15:47:01
【问题描述】:

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

我得到的代码是:

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 的初学者。

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

非常感谢。

【问题讨论】:

标签: javascript getselection


【解决方案1】:

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

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 sample 以获取突出显示用户选择的完整代码,即使跨多个 HTML 元素也是如此。

【讨论】:

    【解决方案2】:

    今天有人问了这个问题:How can I highlight the text of the DOM Range object?

    这是我的答案:

    以下应该做你想做的事。在非 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);
        }
    }
    

    【讨论】:

    • 非常感谢蒂姆,它工作得很好,并为重复道歉。另一个线程没有出现在我的搜索中。
    • 但是如何调用函数 highlight 呢?
    • @LayaleMatta:示例:highlight("#ff0000") 将为当前选定的文本添加红色背景。
    • @TimDown 你能分享一下上面代码的小提琴吗。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2012-08-15
    • 2023-04-09
    • 2021-07-12
    • 2021-04-26
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多