CKEditor 4:如何从插件添加CSS样式表

CKEditor 4: How to add CSS stylesheet from plugin?

本文关键字:添加 CSS 样式 插件 CKEditor      更新时间:2023-09-26

暂时尝试过这个,但没有运气

  editor.addCss(this.path + 'tabber.css');
  editor.document.appendStyleSheet(this.path + 'tabber.css');

完整代码

(function () {
  CKEDITOR.plugins.add('tabber', {
    init: function (editor) {
      editor.ui.addButton('addTab', {
        command: 'addTab',
        icon: this.path + 'icons/tabber.png',
        label: Drupal.t('Insert tabs')
      });
      editor.addCss(this.path + 'tabber.css');
      editor.document.appendStyleSheet(this.path + 'tabber.css');
      editor.addCommand('addTab', {
        exec: function (editor) {
          editor.insertHtml('<dl>' +
            '<dt>Tab title 1</dt>' +
            '<dd><p>Tab content 1.</p></dd>' +
            '<dt>Tab title 2</dt>' +
            '<dd><p>Tab content 2.</p></dd>' +
            '</dl>');
        }
      });
    }
  });
})();

init 中的解决方案(感谢您指出正确方式的答案)

  var cssPath = this.path + 'tabber.css';
  editor.on('instanceReady', function () {
    this.document.appendStyleSheet(cssPath);
  });

CKEDITOR.addCss接受字符串作为参数,因此无法在那里传递任何路径。 CKEDITOR.document.appendStyleSheet是正确的(小提琴):

CKEDITOR.replace( 'editor', {
    on: {
        instanceReady: function() {
            this.document.appendStyleSheet( 'http://path.to.your.css' );
        }
    }
} );

只需确保:

  1. 您的 CSS 存在。
  2. 它具有正确的读取权限。
  3. 编辑器中允许使用 HTML(另请阅读集成指南,因为从 4.1 开始,您需要调整命令的allowedContent)。

我想你可能也会发现 CKEDITOR.getUrl 很有用。

将以下内容添加到 config.js

config.contentCss = [CKEDITOR.getUrl( 'content.css' ), '/path/to/your/css'];

这会将您的 CSS 文件附加到默认的 CKEditor 样式中。与 instanceReady 相比,此方法的优势在于(至少对我而言)当用户将模式从源切换到视觉对象时,instanceReady 事件不会重新触发,并且不会重新应用自定义样式。

如果您使用的是 CKEditor 4.4 或更高版本,则可以使用

editor.addContentsCss( pluginDirectory + 'styles/example.css' );

如果您使用的是 CKEditor 旧版本(如 4.3),则应使用:

beforeInit: function(editor) {
        var ccss = CKEDITOR.config.contentsCss;
        if(typeof ccss == 'string'){
            ccss = [ccss];
        }
        ccss.push('/css/style.css');
        CKEDITOR.config.contentsCss = ccss;
    }

在创建功能时查看此票证:https://dev.ckeditor.com/ticket/11532