命令API
命令API
以下是编辑器命令操作相关的API,使用以下API,最好先要了解浏览器的document.execCommand的相关知识
- editor.command
对document.execCommand执行浏览器基础命令的封装。在二次开发中,如果遇到这种情况,尽量用分装好的edtior.command。例如:
$("#btn").click(function (e) {
    // 注意,下面的 e 参数尽量要传,否则可能导致其他问题
    // 等同于 document.execCommand("bold")
    editor.command(e, "bold");
    
    // 等同于 document.exexCommand("BackColor", false, "#003399")
    editor.command(e, "BackColor", "#003399");
});
- editor.commandForElem
针对当前选中的元素,向上查找,得到符合传入条件的父元素。然后把这个父元素当做选区,来执行命令。除了第一个参数之外,后面的参数和editor.command相同。例如:
$("#btn").click(function (e) {
    // 注意,下面的 e 参数尽量要传,否则可能导致其他问题
    // 针对当前选区所处于的 b strong 元素,然后执行命令
    editor.command("b,strong", e, "bold");
    
    // 为所处的整个 p 元素设置背景色
    editor.command("p", e, "BackColor", "#003399");
});
- editor.customCommand
用于自定义的命令操作,而非document.execCommand提供的基础命令。
注意,建议你对编辑内容的所有修改,都使用命令的方式。如果基础命令满足不了要求,一定要使用这里的自定义命令。不要忽略命令,自己写代码来修改。那样会出现各种问题!!!如果觉得好奇,可以搜索源码中的E.fn.customCommand来看看,自定义命令中那些复杂的操作过程。
程序举例:
$("#btn").click(function (e) {
    // 注意,下面的 e 参数尽量要传,否则可能导致其他问题
    
    editor.command(e, function () {
        // 这里的 this 指向 editor 对象本身
        var editor = this;
        
        editor.$txt.append("<p>自定义命令追加的内容</p>");
    });
});
- editor.queryCommandValue
对document.queryCommandValue的封装,使用方法和document.queryCommandValue一样。分装中,规避了IE8异常错误。
- editor.queryCommandState
对document.queryCommandState的封装,使用方法和document.queryCommandState一样。分装中,规避了IE8异常错误。
- editor.queryCommandSupported
对document.queryCommandSupported的封装,使用方法和document.queryCommandSupported一样。分装中,规避了IE8异常错误。
- editor.commandHooks
当遇到浏览器的document.execCommand不支持的命令时,就需要自定义一个命令,放在editor.commandHooks中。例如,IE浏览器的document.execCommand不支持insertHtml命令,为了保证IE浏览器的可用性,就需要增加这样的hook
editor.commandHooks.insertHtml = function (html) {
    var $elem = $(html);
    var rangeElem = editor.getRangeElem();
    var targetElem;
    
    targetElem = editor.getLegalTags(rangeElem);
    if (!targetElem) {
        return;
    }
    $(targetElem).after($elem);
};

