You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CKEditor 5中添加类似CKEditor 4的自定义样式

CKEditor 5 自定义样式集实现方案

CKEditor 5 没有直接对应 CKEditor 4 中 CKEDITOR.stylesSet.add 的同名API,但其提供的style配置项可实现完全相同的自定义样式效果,操作步骤如下:

1. 确认集成Style插件

常规预置的CKEditor 5构建版本(如经典构建、文档构建)默认已内置Style插件,若为自定义构建的版本,需先安装引入@ckeditor/ckeditor5-style依赖。

2. 定义自定义样式规则

样式规则的定义逻辑和CKEditor 4的stylesSet规则基本兼容,支持指定标签、样式类、内联样式三类核心配置,示例如下:

const myCustomStyles = [
  // 块级样式示例
  {
    name: '提示段落',
    element: 'p',
    classes: ['hint-block', 'p-2', 'border-l-4']
  },
  {
    name: '暗色标题',
    element: 'h3',
    styles: {
      color: '#1e293b',
      fontWeight: 600,
      borderBottom: '1px solid #e2e8f0'
    }
  },
  // 行内样式示例
  {
    name: '高亮标记',
    element: 'span',
    classes: ['bg-yellow-100', 'px-1']
  },
  {
    name: '强调文本',
    element: 'strong',
    styles: {
      color: '#dc2626'
    }
  }
]

3. 注入编辑器配置

在编辑器初始化参数中添加style配置项,同时可将样式按钮添加到工具栏方便调用:

ClassicEditor
  .create( document.querySelector( '#editor' ), {
    style: {
      styles: myCustomStyles
    },
    toolbar: [
      // 原有工具栏配置项
      'heading', 'bold', 'italic', 'bulletedList', 'numberedList',
      // 新增样式选择按钮
      'style'
    ]
  } )

配置完成后,编辑器工具栏的样式下拉菜单会展示所有自定义的样式项,选中内容后点击对应样式即可生效,使用体验和CKEditor 4的自定义样式集完全一致。


内容的提问来源于stack exchange,提问作者CG-root

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 05:15:05