【问题标题】:changing the background color for ckEditor更改 ckEditor 的背景颜色
【发布时间】:2021-08-05 00:55:04
【问题描述】:

我需要在加载时使用我的 ckEditor 动态更改背景颜色 它所在的页面是一个动态加载页面,用户在其中具有特定的 bg 颜色。 我无法加载 css 它必须只是编辑器主体背景颜色

我试过了

window.onload=function(){
    CKEDITOR.instances.editor_data.addCss( 'body { background-color: #efefef; }' );
}

我没有收到错误,但也没有得到任何更改

我也试过了

CKEDITOR.instances.editor_data.addCss( '#cke_editor_data { background-color: #efefef; }' );

【问题讨论】:

    标签: ckeditor


    【解决方案1】:

    如果您在 window.load 期间调用它,则为时已晚,addCss 定义了一些 css 以在创建编辑器时加载,但它不会修改正在运行的实例。

    所以你可以这样做(仅使用 addCSS):

    CKEDITOR.on('instanceCreated', function(e) {
        e.editor.addCss( 'body { background-color: red; }' );
    });
    

    或者这个(处理已编辑文档的更通用的方式)

    CKEDITOR.on('instanceReady', function(e) {
        // First time
        e.editor.document.getBody().setStyle('background-color', 'blue');
        // in case the user switches to source and back
        e.editor.on('contentDom', function() {
            e.editor.document.getBody().setStyle('background-color', 'blue');
        });
    });
    

    【讨论】:

    • @AlfonsosML +1,找到您的答案,效果很好。但是,我在一页上有多个编辑器。你知道如何分别定位每个编辑器吗?
    • 为每个编辑器触发事件​​,并且 e.editor 包含事件引用的编辑器,因此您只需检查它(例如它的名称)来决定如何处理它。
    • 查看 CKeditor v4 的文档,addCss 是 CKEDITOR 对象的方法,但不再是编辑器实例的方法,因此您的第一个方法在 v4 中不起作用。相反,您需要使用editor.document.addCssText()。此外,在您的第二种方法中,您还需要捕获“模式”事件(或代替)“contentDom”,因为在编辑器工具栏中单击 [Source] 两次似乎不会触发 contentDom(我检查过)。在“模式”事件处理程序中,在继续之前检查editor.mode==='wysiwyg':在源代码编辑模式下,editor.document 为空。
    • 糟糕... 2 cmets 前,我应该说editor.document.appendStyleText(),而不是editor.document.addCssText() - 抱歉!
    • 是的,我在一年前回复了一个关于 CKEditor 3 的答案。我没有超能力猜测他们将来打算如何修改 CKEditor 的 API,所以我不知道他们会将 addCss 方法移动到主 CKEDITOR 对象。第二种方法也曾经有效,但它们破坏了其中的一些功能,您可能必须重写它才能使其正常工作。
    【解决方案2】:

    @AlfonsosML 上面的第二个答案非常适合定位编辑器的正文元素。但是我需要在编辑器中定位 a 标签,发现他的第一个答案破坏了它。然后我在 cmets 中尝试了@Doin 提供的解决方案:editor.document.addCssText() 也失败了。 @Doin 已将评论中的代码更正为 editor.document.appendStyleText(),但它被隐藏在上面。我给他的更正投了“有用”的投票,希望其他人能更快地看到它。这对我有用。我的工作代码混合了 2:

    CKEDITOR.on('instanceReady', function(e) {
        // First time
        e.editor.document.getBody().setStyle('background-color', 'rgba(0,0,0,0.59)');
        e.editor.document.getBody().setStyle('color', 'white');
        e.editor.document.getBody().setStyle('text-align', 'center');
        e.editor.document.appendStyleText( 'a { color: white; }' );
        // in case the user switches to source and back
        e.editor.on('contentDom', function() {
            e.editor.document.getBody().setStyle('background-color', 'rgba(0,0,0,0.59)');
            e.editor.document.getBody().setStyle('color', 'white');   
            e.editor.document.getBody().setStyle('text-align', 'center');
            e.editor.document.appendStyleText( 'a { color: white; }' );
        });
    }); 
    

    谢谢

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2013-08-08
      • 1970-01-01
      • 2021-09-03
      • 2012-04-21
      • 2017-08-11
      相关资源
      最近更新 更多