【问题标题】:Adding classes to links in CKeditor向CKeditor中的链接添加类
【发布时间】:2020-01-14 08:14:29
【问题描述】:

我有一些关于在 ckeditor5 中向链接添加类的特定要求 - 我已阅读文档并尝试了多种方法,但我仍然在努力实现我想要的。我的要求是:

  1. 添加的所有链接(无论是使用链接 UI 还是通过粘贴)都必须分配一个类。如果没有指定类或指定的类不在有效类列表中,则该类应设置为defaultClass

  2. 链接类必须在有效链接类列表中

我已经建立了一个包含有效类列表的下拉列表并将其添加到链接 interface

这是我目前的代码:

    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'
    })

【问题讨论】:

标签: javascript ckeditor5


【解决方案1】:

如果您要定义自定义类,请在字段配置中查找 自定义编辑器 JS 样式集,然后输入 .js 文件的路径。

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

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

同时确保您启用了样式工具栏项

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

【讨论】:

  • 我相信这是ck4
【解决方案2】:

decoratorscallback中使用callback函数,使用setTimeout函数检查urls中的有效类列表。

检查jsFiddle。更多信息请参考CKEditor5 manual decorators in Links,并请确认已安装Link插件@ckeditor/ckeditor5-link

希望这会有所帮助。

谢谢

【讨论】:

  • 感谢您的回答,但我不能使用装饰器,因为我想要一个下拉菜单而不是切换开关——我也不相信 setTimeout 是理想的,我认为我们应该使用 CK 来操纵模型直接
【解决方案3】:

解决方案的关键在于 upcast 转换器 - 我最终偶然发现:https://stackoverflow.com/a/55019124/803804

这让我意识到你可以将回调传递给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'
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多