删除DOM中添加的突出显示

时间:2014-01-29 20:07:25

标签: javascript google-chrome google-chrome-extension

我正在使用a script from Tim Down来创建突出显示。现在,我希望用户再次单击浏览器操作以将其删除。

我以为我可以在此代码段中添加另一个if语句:

function makeEditableAndHighlight(colour) {
    var range, 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, '#FFFF00')) {
        document.execCommand("BackColor", false, '#FFFF00');
    }
    if (!document.execCommand("HiliteColor", true, '#FFFF00')) {  // Added this logic
        document.execCommand("removeFormat", false, null);
    }
    document.designMode = "off";
}

我的想法是,如果"HiliteColor"返回true,它会删除格式,但它无效。有什么想法?

修改 在做了更多阅读之后,我了解到execCommand中的布尔值与返回值没有任何关系。如何改进逻辑以反转背景颜色?它甚至可行吗?

1 个答案:

答案 0 :(得分:3)

您需要一种“序列化”所选范围以供日后访问的方法 This answer 解释了如何实现序列化/反序列化。

您的代码可能如下所示:

var serializedRange;

/* Serializes and returns the specified range
 * (ignoring it if its length is zero) */
function serializeRange(range) {
    return (!range || ((range.startContainer === range.endContainer)
                       && (range.startOffset === range.endOffset)))
            ? null : {
                startContainer: range.startContainer,
                startOffset:    range.startOffset,
                endContainer:   range.endContainer,
                endOffset:      range.endOffset
            };
}

/* Restores the specified serialized version
 * (removing any ranges currently seleted) */
function restoreRange(serialized) {
    var range = document.createRange();
    range.setStart(serialized.startContainer, serialized.startOffset);
    range.setEnd(serialized.endContainer, serialized.endOffset);

    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

/* Hilites the currently selected range or removes the hilite
 * (if there is a previously serialized range) */
function toggleHilite() {
    document.designMode = 'on';

    var sel = window.getSelection();
    if (serializedRange) {
        /* There is a hilited range, let's remove the hilite */
        restoreRange(serializedRange);
        serializedRange = null;
        document.execCommand('removeFormat', false, null);
        sel.removeAllRanges();
    } else {
        /* There is no hilited range, so hilite
         * the currently selected range (if any) */
        if (sel.rangeCount && sel.getRangeAt) {
            document.execCommand('hiliteColor', false, '#FFFF00');
            serializedRange = serializeRange(sel.getRangeAt(0));
            // it is important to serialize the range *after* hiliting,
            // because `execCommand` will change the DOM affecting the
            // range's start-/endContainer and offsets.
        }
    }

    document.designMode = 'off';
}