咨询CKEditor5无上传图片工具栏:需插入自定义属性IMG标签是否需自研插件
解答
标准CKEditor5的官方构建里确实没有能直接输入所有自定义属性(src/height/width/class)插入img标签的可视化组件,你没漏看。默认的「插入图片URL」功能只支持输入图片地址,没法直接设置高度、宽度、类名这类额外属性。
不用完全从零开发插件,有两种更省事的方案:
扩展现有图片插入对话框:
基于默认的ImageInsert插件,通过CKEditor5的API给插入对话框加额外输入字段(高度、宽度、类名),插入时把这些属性绑定到img元素上。核心代码示例如下:class CustomImageInsert extends Plugin { init() { const editor = this.editor; editor.plugins.get('ImageInsert').on('dialog:setup', (evt, data) => { const dialog = data.dialog; // 添加宽度输入项 dialog.addContent({ type: 'text', label: '宽度(像素)', id: 'width', validate: val => val ? !isNaN(parseInt(val)) : true }); // 添加类名输入项 dialog.addContent({ type: 'text', label: 'CSS类名', id: 'class' }); // 重写提交逻辑,应用自定义属性 dialog.on('submit', (evt) => { const { src, width, class: className } = dialog.getValue(); editor.model.change(writer => { const attrs = { src }; if (width) attrs.width = `${width}px`; if (className) attrs.class = className; const image = writer.createElement('imageBlock', attrs); editor.model.insertContent(image, editor.model.document.selection); }); evt.stop(); // 覆盖默认插入逻辑 }); }); } }之后在编辑器配置里注册这个自定义插件,同时禁用所有上传相关插件(比如
ImageUpload、SimpleUploadAdapter)就行。启用源码编辑模式:
如果需求不算复杂,直接开启CKEditor5的SourceEditing插件,让用户在源码视图里手动写带自定义属性的img标签,写完切回可视化模式就能正常显示。这种方式不用写代码,适合简单场景。
要是这两种方案都不符合你的需求,再考虑完全自定义独立插件,不过工作量会大不少。
内容的提问来源于stack exchange,提问作者Nik Dow
相关产品推荐
相关产品推荐

