返回

CkEditor 5 上传图像内联样式如何去除?

javascript

使用 CkEditor 5 移除上传图像的内联样式

问题

在使用 CkEditor 5 时,上传图像后,这些图像可能会自动添加内联样式,例如 style="aspect-ratio:800/445;"。这会导致图像在编辑器中显示不正确,或在发布后出现布局问题。

解决方案

使用 CkEditor 5 的 image-style 插件可以解决此问题。此插件让你可以控制上传图像的样式。

安装和使用 image-style 插件

  1. 安装插件:
npm install --save @ckeditor/ckeditor5-image-style
  1. 配置 CkEditor 5:
    在你的 CkEditor 5 配置中添加 image-style 插件:
ClassicEditor
    .create(document.querySelector('#news-editor'), {
        ...
        toolbar: [
            // ... other toolbar items
            'imageStyle', // Add the imageStyle plugin to the toolbar
        ],
        image: {
            style: {
                default: 'alignLeft', // Set the default image style
                styles: [
                    'alignLeft',
                    'alignCenter',
                    'alignRight',
                ]
            }
        }
    })
  1. 使用插件:
// 获取图像样式命令
const imageStyleCommand = editor.commands.get('imageStyle');

// 设置图像样式为 'alignCenter'
imageStyleCommand.execute('alignCenter');

注意事项

  • 确保使用最新版本的 CkEditor 5 和 image-style 插件。
  • 此解决方案仅适用于上传的图像。

常见问题解答

  1. 为什么我仍然看到图像上有内联样式?

    • 确保你正确安装和配置了 image-style 插件。
    • 检查图像源代码,确保没有其他样式覆盖 image-style 插件的设置。
  2. image-style 插件支持哪些图像样式?

    • 此插件支持基本的图像样式,如对齐(居左、居中、居右)。你还可以自定义样式以满足你的特定需求。
  3. 我可以在上传图像后更改图像样式吗?

    • 是的,使用 imageStyleCommand 命令,你可以在上传图像后随时更改其样式。
  4. 此解决方案是否适用于所有浏览器?

    • 是的,image-style 插件兼容所有现代浏览器。
  5. 是否存在其他解决此问题的插件?

    • 除了 image-style 插件外,还有一些其他第三方插件可以提供类似的功能。然而,这些插件可能不适合所有项目。