开发者

execCommand without a selection? (set font, size etc)

开发者 https://www.devze.com 2023-03-17 17:46 出处:网络
I can get my custom WYSIWYG editor to apply styling to selected text no problem: pnlDocumentEditor_IFrame.document.execCom开发者_运维知识库mand(cmd, ui, opt)

I can get my custom WYSIWYG editor to apply styling to selected text no problem:

pnlDocumentEditor_IFrame.document.execCom开发者_运维知识库mand(cmd, ui, opt)

.. but what I need to be able to do is allow the user to set a font, or font size, or bold etc so that text typed AFTER this command is issued will have that style applied.

Is this possible? All execCommands I've tried seem to only work on selected text.


Appling execCommand on certain element, WITHOUT selecting it with mouse, can be done with this function:

jsFiddle example

function execCommandOnElement(el, commandName, value) {
    if (typeof value == "undefined") {
        value = null;
    }

    if (typeof window.getSelection != "undefined") {
        // Non-IE case
        var sel = window.getSelection();

        // Save the current selection
        var savedRanges = [];
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            savedRanges[i] = sel.getRangeAt(i).cloneRange();
        }

        // Temporarily enable designMode so that
        // document.execCommand() will work
        document.designMode = "on";

        // Select the element's content
        sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);

        // Execute the command
        document.execCommand(commandName, false, value);

        // Disable designMode
        document.designMode = "off";

        // Restore the previous selection
        sel = window.getSelection();
        sel.removeAllRanges();
        for (var i = 0, len = savedRanges.length; i < len; ++i) {
            sel.addRange(savedRanges[i]);
        }
    } else if (typeof document.body.createTextRange != "undefined") {
        // IE case
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.execCommand(commandName, false, value);
    }
}

And example usage:

var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");

Source: set execcommand just for a div

0

精彩评论

暂无评论...
验证码 换一张
取 消