通过CDN使用CKEditor5,如何访问DropdownButtonView等UI组件工具?
解决CKEditor5 CDN模式下访问Dropdown相关特性的问题
核心原理
CKEditor5的CDN构建版本会将所有模块暴露在全局CKEditor5对象下,而非通过编辑器实例内部属性访问。你需要直接从全局对象中获取对应的类和工具函数,路径与npm导入路径一一对应。
正确访问方式
以下是你需要的特性对应的全局访问路径:
ButtonView→CKEditor5.ui.button.ButtonViewDropdownButtonView→CKEditor5.ui.button.DropdownButtonViewDropdownView→CKEditor5.ui.dropdown.DropdownViewcreateDropdown、addListToDropdown→CKEditor5.ui.dropdown.utils下的方法
修正后的示例代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CKEditor 5 Customization</title> <!-- 使用官方CDN的Classic Build,已包含ui模块 --> <script src="https://cdn.ckeditor.com/ckeditor5/35.0.1/classic/ckeditor.js"></script> </head> <body> <div id="editor"> <p>This is the editor content.</p> </div> <script> ClassicEditor .create(document.querySelector('#editor'), { toolbar: { items: [ 'heading', '|', 'bold', 'italic', '|', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'insertTable', '|', 'undo', 'redo' ] }, language: 'en' }) .then(editor => { console.log('Editor was initialized', editor); const locale = editor.locale; // 正确获取所需特性 const ButtonView = CKEditor5.ui.button.ButtonView; const DropdownButtonView = CKEditor5.ui.button.DropdownButtonView; const DropdownView = CKEditor5.ui.dropdown.DropdownView; const { createDropdown, addListToDropdown } = CKEditor5.ui.dropdown.utils; // 示例:创建一个简单的Dropdown const dropdown = createDropdown(locale); addListToDropdown(dropdown, [ { type: 'button', model: { label: 'Option 1', withText: true, onExecute: () => { console.log('Option 1 clicked'); } } }, { type: 'button', model: { label: 'Option 2', withText: true, onExecute: () => { console.log('Option 2 clicked'); } } } ]); // 将Dropdown添加到工具栏 editor.ui.componentFactory.add('customDropdown', () => dropdown); editor.ui.toolbar.addItems('customDropdown'); }) .catch(error => { console.error(error); }); </script> </body> </html>
错误方案解析
- 方案一错误:
editor.ui.componentFactory.create()是用来创建已注册的UI组件(如工具栏内置按钮),而非获取底层的类或工具函数,因此无法通过它拿到DropdownButtonView、createDropdown等。 - 方案二错误:
editor.ui仅包含编辑器UI的实例化组件和工厂方法,并不暴露底层的UI类定义,这些类都挂载在全局CKEditor5对象下。
内容的提问来源于stack exchange,提问作者Rafaqat
相关产品推荐
相关产品推荐

