为一个div设置execcommand

mko*_*twd 8 javascript execcommand

它有任何方法绑定execcommand与div元素而不是整个文档,我试试这个:

document.getElementById('div').execcommand(...)
Run Code Online (Sandbox Code Playgroud)

但它有一个错误:

execcommand is not a function
Run Code Online (Sandbox Code Playgroud)

它有任何方法绑定execcommand只有div元素而不是整个文件!! 我不喜欢使用iframe方法.

Tim*_*own 18

这在IE中比其他浏览器更容易,因为IE的TextRange对象有一个execCommand()方法,这意味着可以在文档的一部分上执行命令而无需更改选择并暂时启用designMode(这是您在其他浏览器中必须执行的操作) ).这是一个干净利落的功能:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

var testDiv = document.getElementById("test");
execCommandOnElement(testDiv, "Bold");
execCommandOnElement(testDiv, "ForeColor", "red");
Run Code Online (Sandbox Code Playgroud)