简体   繁体   English

如何在没有css文件的情况下将css动态添加到ckeditor

[英]How to dynamically add css to ckeditor without a css file

I have a situation where I am storing dynamic css data about a text object in a database as json.我有一种情况,我将有关文本对象的动态 css 数据作为 json 存储在数据库中。 I need to map that same css data into styles in CKEditor.我需要将相同的 css 数据映射到 CKEditor 中的样式。 I am successfully able to load the classes into the CKEDITOR styles dropdown by parsing the json into the style set by running:通过运行以下命令将 json 解析为样式集,我能够成功地将类加载到 CKEDITOR 样式下拉列表中:

CKEDITOR.stylesSet.add('myStyles',styleObj);

Unfortunately this does not fully work with the onscreen text because the css does not exists as a file.不幸的是,这并不完全适用于屏幕文本,因为 css 不作为文件存在。

I've also successfully generate the css into the head of the dom by appending the dynamically generated css to a style tag.我还通过将动态生成的 css 附加到样式标记,成功地将 css 生成到 dom 的头部。 Unfortunately this still does not connect the actual css generated to the CKEDITOR because it is in a separate context.不幸的是,这仍然没有将生成的实际 css 连接到 CKEDITOR,因为它处于单独的上下文中。

Does anyone know how I can either connect document level css to the CKEDITOR instance or generate the CSS in a way that CKEDITOR understands?有谁知道我如何将文档级 css 连接到 CKEDITOR 实例或以 CKEDITOR 理解的方式生成 CSS? I'd prefer not to write a temporary CSS file to disk for every single user who needs to view the text object.我不希望为每个需要查看文本对象的用户将临时 CSS 文件写入磁盘。

I figured out the answer to this by using the CKEDITOR.addCss() function.我通过使用 CKEDITOR.addCss() 函数找到了答案。 Instead of trying to load the css into the document head as styles, the process can be much simpler by running CKEDITOR.addCss() function.通过运行 CKEDITOR.addCss() 函数,该过程可以简单得多,而不是尝试将 css 作为样式加载到文档头中。

The code looks like:代码如下:

for each css style found in the json:对于在 json 中找到的每个 css 样式:

    styleObj.push({name:this.name,element:'p',attributes: { 'class':cssClassName}});
    var cssSheetString = '.'+cssClassName+' {font-family:'+this.fontFamily+'; font-size:'+fontSize+'; font-weight:'+this.fontStyle+'; text-decoration:'+textDecoration+'; } ';
    CKEDITOR.addCss(cssSheetString);

after the loop ends then also add the styles object:循环结束后,还要添加样式对象:

if(!CKEDITOR.stylesSet.registered.myStyles){
                CKEDITOR.stylesSet.add('myStyles',styleObj);
            }

Just for posterity.只为后人。 I've seen answers that say this will work我已经看到答案说这会起作用

    CKEDITOR.on('instanceCreated', function (event) {
        event.editor.addCss(styles);
    });

but it does not, you have to use但事实并非如此,您必须使用

    CKEDITOR.on('instanceCreated', function (event) {
        CKEDITOR.addCss(styles);
    });

also if your styles variable changes you have to destroy and recreate your ckeditor instance with the new styles.此外,如果您的样式变量更改,您必须销毁并使用新样式重新创建 ckeditor 实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM