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

Strapi自定义CKEditor5插件问题:自定义Div被替换为P标签

解决Strapi CKEditor5中自定义带类div被替换为p标签的问题

问题根源

你当前的问题出在两个核心点:

  1. 自定义模型simpleBoxDescription的allowIn配置仅允许在simpleBox内部插入,但实际是往编辑器根节点插入该元素,不符合Schema规则,CKEditor会自动将不合法元素转换为默认的p标签。
  2. 通过customSectionPlugin直接插入HTML代码时,CKEditor的内容解析器会优先按默认规则处理未注册元素,不会触发你定义的upcast转换逻辑。

解决方案

1. 修正模型Schema配置

修改editor.model.schema.register中的allowIn属性,让自定义模型能在编辑器根节点($root)中存在:

editor.model.schema.register("simpleBoxDescription", {
  isLimit: true,
  // 允许在根节点和simpleBox中插入
  allowIn: ["$root", "simpleBox"],
  allowContentOf: "$root",
});

2. 修改插入逻辑:使用模型元素而非直接插入HTML

放弃直接插入HTML的方式,改用CKEditor模型API创建并插入自定义节点,确保编辑器识别这是合法元素:

// 调整你的handleToggleCustomSectionClick函数
const handleToggleCustomSectionClick = () => {
  if (!editorInstance) return;

  editorInstance.model.change(writer => {
    // 创建自定义模型元素
    const simpleBoxDesc = writer.createElement("simpleBoxDescription");
    // 往元素内添加默认段落和文本
    const defaultPara = writer.createElement("paragraph");
    writer.append(writer.createText("Should be formatted section..."), defaultPara);
    writer.append(defaultPara, simpleBoxDesc);
    
    // 将元素插入到当前光标位置
    editorInstance.model.insertContent(simpleBoxDesc);
    // 把光标定位到自定义元素内部
    writer.setSelection(simpleBoxDesc, "in");
  });
};

3. 保留现有转换规则(无需修改)

你当前定义的upcast、dataDowncast、editingDowncast转换规则是正确的,它们会确保模型元素在编辑视图和数据输出时,正确转换为带指定类的div元素。

额外检查

  • 确认自定义CSS已正确加载,在编辑视图中能看到样式效果
  • 不要尝试使用CKEditor4的enterMode等配置项,CKEditor5完全基于Schema和模型工作,这类旧配置已被移除

内容的提问来源于stack exchange,提问作者user1621949

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:23:10