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

如何在CKEditor5中通过自定义插件按钮追加内容并移动光标

CKEditor5 插入自定义内容并定位光标到末尾的实现方法

问题描述

我需要在CKEditor5中通过自定义插件按钮插入一段HTML代码:

<div title=" + parts[0]+ " id=" + parts[1]+ " class="galleryPlaceholder"><p>&nbsp;</p></div><p></p>

要求在光标所在位置插入这段内容,且插入后光标自动移动到最后一个<p></p>内部。目前使用editor.data.set()会替换编辑器全部内容,找不到合适的实现方法。

当前代码:

this.listenTo( this.gallerySelect, 'execute', evt => {
    const whole = evt.source.val;
    
    let parts = whole.split(' ');
    editor.data.set("<div title=\"" + parts[0] + "\" id=\"" + parts[1] + "\" class=\"galleryPlaceholder\"><p>&nbsp;</p></div><p></p>");
} );

解决方案

核心修改思路

  1. 替换editor.data.set():该方法用于覆盖整个编辑器内容,改用editor.model.insertContent()实现光标位置插入。
  2. 适配CKEditor5的MVVM架构:需要将HTML先转为视图片段,再转换为模型片段才能插入。
  3. 光标定位:插入后找到最后一个空<p>对应的模型节点,将光标设置到该节点末尾。

修改后的代码

this.listenTo( this.gallerySelect, 'execute', evt => {
    const whole = evt.source.val;
    const parts = whole.split(' ');

    // 处理参数不足的情况,避免报错
    if (parts.length < 2) return;

    // 构建目标HTML字符串
    const html = `<div title="${parts[0]}" id="${parts[1]}" class="galleryPlaceholder"><p>&nbsp;</p></div><p></p>`;

    // 将HTML转为CKEditor5可识别的模型片段
    const viewFragment = editor.data.processor.toView(html);
    const modelFragment = editor.data.toModel(viewFragment);

    // 在光标位置插入内容
    editor.model.insertContent(modelFragment);

    // 定位光标到最后一个<p>的末尾
    const lastNode = modelFragment.children[modelFragment.children.length - 1];
    if (lastNode) {
        editor.model.change(writer => {
            writer.setSelection(lastNode, 'end');
        });
    }
} );

关键说明

  • editor.model.insertContent():CKEditor5官方推荐的内容插入方法,会保留原有内容并在光标位置插入新内容。
  • 模型与视图转换:CKEditor5的编辑操作基于模型层,必须将HTML转换为模型片段才能正确插入和渲染。
  • 光标定位逻辑:通过modelFragment.children获取插入的所有节点,取最后一个节点(对应空<p>),使用writer.setSelection()将光标设置到该节点的末尾位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:49:52