CKEditor 5中使用writer.setAttribute为img设置title属性无效问题
解决CKEditor 5中无法为图片设置title属性的问题
你遇到的核心问题是CKEditor 5的模型-视图分离机制导致的——虽然你在模型上设置了title属性,但如果没有配置对应的转换器,编辑器不会自动把这个属性同步到视图中的<img>元素上。另外,Schema的配置也需要确保明确允许image元素拥有title属性,可能你之前的schema.extend用法不够完整。
下面是完整的修复步骤,结合你的代码进行修改:
步骤1:配置Schema允许title属性
首先,在插件的init方法中扩展编辑器的Schema,明确告知模型系统image元素可以持有title属性:
editor.model.schema.extend('image', { allowAttributes: 'title' });
这一步是基础,只有Schema允许的属性,模型才能正确存储和处理。
步骤2:添加模型到视图的转换器
CKEditor 5不会自动将模型属性映射到视图,需要手动添加**向下转换(downcast)**的转换器,把模型中的title属性同步到视图的<img>元素上:
editor.conversion.for('downcast').attributeToAttribute({ model: 'title', view: 'title', converterPriority: 'low' });
如果需要支持从HTML粘贴图片时,自动把<img>的title属性同步到模型中,还可以添加**向上转换(upcast)**的转换器:
editor.conversion.for('upcast').attributeToAttribute({ view: { name: 'img', key: 'title' }, model: 'title', converterPriority: 'low' });
步骤3:整合配置后的完整插件代码
把以上配置加入你的插件,同时增加选中元素的类型校验,让代码更健壮:
const ButtonView = require('@ckeditor/ckeditor5-ui/src/button/buttonview').default; const imageIcon = require('@ckeditor/ckeditor5-core/theme/icons/low-vision.svg').default; export default class ImageTextTitle extends Plugin { init() { const editor = this.editor; // 允许image元素拥有title属性 editor.model.schema.extend('image', { allowAttributes: 'title' }); // 模型到视图的转换器 editor.conversion.for('downcast').attributeToAttribute({ model: 'title', view: 'title', converterPriority: 'low' }); // 可选:视图到模型的转换器(支持粘贴图片时同步title) editor.conversion.for('upcast').attributeToAttribute({ view: { name: 'img', key: 'title' }, model: 'title', converterPriority: 'low' }); editor.ui.componentFactory.add('imageTextTitle', locale => { const view = new ButtonView(locale); view.set({ label: 'Insert image title', icon: imageIcon, tooltip: true }); view.on('execute', () => { const newTitle = prompt('New image title'); const selection = editor.model.document.selection; const imageElement = selection.getSelectedElement(); // 校验:确保选中的是image元素且输入不为空 if (newTitle !== null && imageElement && imageElement.is('image')) { editor.model.change(writer => { writer.setAttribute('title', newTitle, imageElement); }); } }); return view; }); } }
补充说明
- 为什么
alt属性可以正常工作?因为CKEditor 5的内置图片插件已经为alt属性配置好了完整的Schema规则和转换器,不需要手动处理。 - 新增的
imageElement.is('image')校验可以避免选中非图片元素时执行无效操作,提升代码稳定性。
现在重新加载编辑器,选中图片后点击按钮设置title,就能在视图的<img>元素上看到对应的title属性了。
内容的提问来源于stack exchange,提问作者gonepostal
相关产品推荐
相关产品推荐

