CKEditor4添加自定义按钮,创建自定义插件

710 阅读1分钟

这里会提到两种添加自定义按钮的方式,都是基于创建插件添加的。

1.创建基本插件

关于创建基本插件官方有一个小案例,大家可以去看一看:用 20 行代码创建 CKEditor 4 插件

 
CKEDITOR.plugins.add('horizontaldashed', {
  icons: 'horizontaldashed', // 图标
  init: function (editor) {
    editor.addCommand('horizontaldashed', { // 创建插件,插件的名称会在启用插件的时候使用
      exec: function (editor) {
        // 点击按钮后悔触发回调
        editor.insertHtml('<hr style="border: 1px dashed" />'); // 向富文本中添加的文本
      }
    });
    editor.ui.addButton('HorizontalDashed', { // 添加按钮,按钮的名称会在添加按钮的时候使用
      label: '插入水平虚线', // 鼠标悬浮在按钮上时显示的文字
      command: 'horizontaldashed', // 这里写插件的名称
      toolbar: 'insert' // 按钮的位置,也可以在启用的时候设置位置
    });
  }
});

大概效果如下:

2.下拉菜单形式的插件

 
CKEDITOR.plugins.add('templecustomize', {
  icons: 'templecustomize', // 图标
  init: function (editor) {
    editor.ui.addRichCombo('TempleCustomize', { // 按钮名称,启用按钮时的名称
      label: '模版', // 下拉菜单的名称
      title: '模版',
      toolbar: 'insert',
      panel: {
        css: ['/ckeditor/plugins/templecustomize/css/index.css'], // 插件的样式
        multiSelect: false,
        attributes: { 'aria-label': '模版' }
      },
      init: function () {
        // 点击插件按钮时会触发回调
        this.startGroup('选择模板'); // 下拉分组
        this.add('value', 'label') // 下拉的选项
      },
      onClick: function (value) {
        // 点击下拉选项时会触发回调
        editor.insertHtml(value)
      }
    })
  }
});

效果如下:

这里需要注意的是,无论哪种插件,插件的名称和图标的名称是要和文件夹名称保持一致的,另外文件夹内的结构也是固定的,自定义插件要放在public\ckeditor\plugins\路径下,icons中是要显示的图标,plugin.js是具体代码