将 类 添加到 CKeditor 中的链接

Adding classes to links in CKeditor

我有一些关于在 ckeditor5 中将 classes 添加到 links 的具体要求 - 我已经阅读了文档并尝试了多种方法,但我仍在努力实现我想要的。我的要求是:

  1. 添加的所有 link(无论是使用 link UI 还是通过粘贴)都必须分配 class。如果未分配 class 或分配的 class 不在有效 classes

    列表中,则 class 应设置为 defaultClass
  2. Link classes 必须在有效列表中 link classes

我构建了一个包含有效 classes 列表的下拉列表,并将其添加到 link 界面

这是我目前的代码:

    const { editor } = this

    const linkClasses = editor.config.get('link.options.classes')
    const defaultLinkClass = editor.config.get('link.options.defaultClass')

    editor.model.schema.extend('$text', { allowAttributes: 'linkClass' })

    editor.conversion.for('downcast').attributeToElement({
      model: 'linkClass',
      view: (attributeValue, writer) => writer.createAttributeElement('a', { class: attributeValue }, { priority: 5 }),
      converterPriority: 'low'
    })

    editor.conversion.for('upcast').attributeToAttribute({
      view: {
        name: 'a',
        key: 'class'
      },
      model: 'linkClass',
      converterPriority: 'low'
    })

如果您要定义自定义 class,请在字段配置中查找 Custom Editor JS Styles Set 并输入 .js 文件的路径。

在此文件中,您可以像这样定义自定义样式:

CKEDITOR.stylesSet.add
( 'mystyles', 
    [ 
        { name: 'Bootstrap Blockquote', 
          element: 'blockquote', 
          attributes: { 'class': 'blockquote' }
        },
    ] 
);

还要确保您启用了 样式 工具栏项

您还应该使用编辑器的样式功能检查样式 here

decoratorscallback中使用callback函数,在[=14=中使用setTimeout函数检查有效的class列表].

检查 jsFiddle. Refer CKEditor5 manual decorators in Links for more and please confirm the Link 插件安装 @ckeditor/ckeditor5-link

希望这会有所帮助。

谢谢

解决方案的关键在于向上转换转换器——我最终偶然发现:

这让我意识到您可以将回调传递给 attributeToAttribute 转换器 https://ckeditor.com/docs/ckeditor5/latest/api/module_engine_conversion_upcasthelpers-UpcastHelpers.html#function-attributeToAttribute

最后真的很简单:

editor.conversion.for('upcast').attributeToAttribute({
  view: {
    name: 'a',
    key: 'class'
  },
  model: {
    key: 'linkClass',
    value: viewElement => {
      if(this.classes.includes(viewElement.getAttribute('class'))) {
        return viewElement.getAttribute('class')
      } else {
        return this.defaultClass
      }
    }
  },
  converterPriority: 'low'
})