Javascript Quandary: Creating a highlighter pen tool… almost there

前端 未结 1 1596
暖寄归人
暖寄归人 2021-01-03 08:05

I\'m working on a little JS plugin that I want to function exactly like a real highlighter pen. Take a standard div of html text (with children), select text with mouse, and

1条回答
  •  生来不讨喜
    2021-01-03 08:40

    Actually, this is reasonably straightforward using document.execCommand(). It's slightly complicated by the fact that you need to temporarily make the document editable in non-IE browser for document.execCommand() to work, which in turn destroys the selection in some browsers, but that's easy enough to work around. It works in all major browsers, including IE 6.

    UPDATE: Fixed for IE 9.

    jsFiddle: http://jsfiddle.net/timdown/Hp7Zs/32/

    Code:

    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, colour)) {
            document.execCommand("BackColor", false, colour);
        }
        document.designMode = "off";
    }
    
    function highlightSelection(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);
        }
    }
    

    0 讨论(0)
提交回复
热议问题