execCommand没有选择? (设置字体,大小等)

时间:2011-07-07 09:01:08

标签: wysiwyg execcommand

我可以让我的自定义WYSIWYG编辑器将​​样式应用于所选文本没问题:

pnlDocumentEditor_IFrame.document.execCommand(cmd, ui, opt)

..但我需要做的是允许用户设置字体,字体大小或粗体等,以便在发出此命令后键入的文本将应用该样式。

这可能吗?我试过的所有execCommands似乎只适用于选定的文本。

1 个答案:

答案 0 :(得分:0)

在某些元素上应用execCommand,不用鼠标选择它,可以用这个函数完成:

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

示例用法:

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

来源:set execcommand just for a div