gpt4 book ai didi

ckeditor5 使用属性创建元素 "image"

转载 作者:行者123 更新时间:2023-12-04 15:44:45 33 4
gpt4 key购买 nike

我正在尝试创建一个自定义插件来从我已经构建的媒体浏览器中插入图像。我想为图像附加一些属性。无论我尝试什么,它都只会插入带有 src 的图像和 alt属性。换句话说,我的图像总是缺少 data-sourceclass属性。我已经尝试将数据属性键设为 dataSource但这也不起作用。

const imageElement = writer.createElement( 'image',  {
'src': src,
'alt': alt,
'data-sources': dataSources,
'class': cls
} );
editor.model.insertContent( imageElement, editor.model.document.selection );

任何想法或建议将不胜感激。

最佳答案

您需要做两件事来处理图像的新属性。

首先,您需要扩展the schema使用适当的规则通知模型在编辑器中允许给定的属性。

第二件事是通知编辑如何convert给定模型结构的属性,反之亦然,使用适当的转换器。

不幸的是,图像转换器相当复杂,因为图像总是用 <figure> 包裹起来。 .您可以在下面找到代码和指向如何创建此类转换器的工作示例的链接(转换器是基于 CKEditor5 图像插件的 source code 创建的)。就本示例而言,data-source属性在模型中存储为 dSource图像元素的属性。

editor.model.schema.extend( 'image', { allowAttributes: 'dSource' } );

editor.conversion.for( 'upcast' ).attributeToAttribute( {
view: 'data-source',
model: 'dSource'
} );

editor.conversion.for( 'downcast' ).add( dispatcher => {
dispatcher.on( 'attribute:dSource:image', ( evt, data, conversionApi ) => {
if ( !conversionApi.consumable.consume( data.item, evt.name ) ) {
return;
}

const viewWriter = conversionApi.writer;
const figure = conversionApi.mapper.toViewElement( data.item );
const img = figure.getChild( 0 );

if ( data.attributeNewValue !== null ) {
viewWriter.setAttribute( 'data-source', data.attributeNewValue, img );
} else {
viewWriter.removeAttribute( 'data-source', img );
}
} );
} );

工作样本链接: https://codepen.io/msamsel/pen/pXKRed?editors=1010

关于ckeditor5 使用属性创建元素 "image",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402202/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com