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

CKEditor5:在只读模式下启用源代码视图的方案咨询

实现只读但支持源代码视图的CKEditor5(无需自定义插件)

不用官方的只读模式,而是手动控制编辑区域的可编辑性,结合编辑器模式切换事件来处理源代码视图的只读状态,具体思路如下:

核心思路

  1. 跳过CKEditor官方的editor.isReadOnly = true设置(该设置会禁用所有编辑类插件,包括源代码编辑),手动将可视化编辑区设为只读。
  2. 监听编辑器的change:mode事件,在切换到源代码视图时,将对应的文本框设为只读;切回可视化视图时,重新确保编辑区只读。
  3. 可选:禁用其他无关的工具栏按钮,避免用户产生误解。

代码实现示例

ClassicEditor
    .create(document.querySelector('#editor'), {
        plugins: ['SourceEditing', 'Essentials', 'Paragraph', 'Bold', 'Italic'], // 根据需求添加插件
        toolbar: ['sourceEditing', 'bold', 'italic'] // 保留需要的工具栏按钮
    })
    .then(editor => {
        // 初始化时设置可视化编辑区为只读
        const editableRoot = editor.editing.view.getDomRoot();
        editableRoot.setAttribute('contenteditable', 'false');

        // 监听模式切换事件
        editor.on('change:mode', () => {
            if (editor.mode === 'source') {
                // 定位源代码视图的文本框
                const sourceTextarea = editor.ui.view.element.querySelector('.ck-source-editor__textarea');
                if (sourceTextarea) {
                    sourceTextarea.setAttribute('readonly', 'readonly');
                    sourceTextarea.style.backgroundColor = '#f5f5f5'; // 视觉提示只读状态
                }
            } else {
                // 切回可视化视图时重新锁定编辑区
                const editableRoot = editor.editing.view.getDomRoot();
                editableRoot.setAttribute('contenteditable', 'false');
            }
        });
    })
    .catch(error => {
        console.error(error);
    });

辅助优化(可选)

如果需要禁用除源代码按钮外的其他工具栏按钮,可添加CSS:

/* 禁用非源代码编辑按钮 */
.ck-toolbar .ck-button:not(.ck-source-editing-button) {
    pointer-events: none;
    opacity: 0.6;
}

注意事项

  • ck-source-editor__textarea是SourceEditing插件默认的文本框类名,若插件版本特殊,可通过DOM结构定位(比如找编辑器容器内的textarea元素)。
  • 监听change:mode事件比直接监听按钮点击更可靠,能覆盖快捷键切换模式等场景。
  • 这种方法完全基于CKEditor现有API和DOM操作,无需编写自定义插件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:30:11