如何从外部颜色选择器动态更改Ckeditor实例的背景颜色

时间:2013-12-09 01:43:42

标签: ckeditor color-picker jquery

我在CMS中的容器上使用了一些外部样式,其中一个是css背景颜色,然后我们使用CKEditor(4.x)实例来管理内容中的内容容器。一个问题是,当您希望容器具有黑色(#000)背景但编辑器具有标准白色(#FFF)背景并且您想要使用白色文本时,您显然无法看到该文本编辑没有MacGyvering你工作时的一些假背景,或者使用不同的颜色文本,然后改为白色....任何你旋转它的方式,它是一个PITA,当然不是用户友好。

所以我们正在做的是使用外部表单字段中颜色选择器的更改事件来触发一个动态更改编辑器实例背景的函数。我从上一个问题(changing the background color for ckEditor)得到了这个基础:

set_background: function(hex) {
    if (typeof CKEDITOR !== "object") { return; }
    var editor = CKEDITOR.instances['body'];
    if (editor) {
        editor.on('instanceReady', function(e) {
            // First time
            e.editor.document.getBody().setStyle('background-color', hex);
            // in case the user switches to source and back
            e.editor.on('contentDom', function() {
                e.editor.document.getBody().setStyle('background-color', hex);
            });
        });
    }
}

该方法在表单加载时触发一次,这非常有效,无论加载时颜色选择器中的值是否正确设置,编辑器都继承该背景颜色。但是,当我更改选择器的颜色时,它不会更新实例。但是,如果我删除instanceReady支票,它会反过来,加载功能将无效,但对选择器的任何更改都能正常工作。

我猜测ck实例在我的第二个场景的第一次调用期间还没有准备好,这意味着我可能必须在那里使用它,所以我的问题是,如何使得后续调用正常运行,就像第一个打电话给它吗?

感谢您的任何见解!

1 个答案:

答案 0 :(得分:2)

我设法找到一个可以在实例准备好后存储该实例的工作解决方案,并将其用于将来的任何调用......

ck_instance: null,

set_background: function(hex) {
    if (this.ck_instance === null) {
        if (typeof CKEDITOR !== "object") { return; }
        this.ck_instance = CKEDITOR.instances['body'];
        if (typeof this.ck_instance !== "object") { return; }
        this.ck_instance.on('instanceReady', function(e) {
            // First time
            e.editor.document.getBody().setStyle('background-color', hex);
            // in case the user switches to source and back
            e.editor.on('contentDom', function() {
                e.editor.document.getBody().setStyle('background-color', hex);
            });
        });
        return;             
    }
    // First time
    this.ck_instance.document.getBody().setStyle('background-color', hex);
    // in case the user switches to source and back
    this.ck_instance.on('contentDom', function() {
        this.ck_instance.document.getBody().setStyle('background-color', hex);
    });
}

现在两个必需的点火工作都有效,一旦表格加载就在新编辑器中设置保存的背景,再次通过颜色选择器更改回调。