如何正确配置Jodit工具栏按钮的自定义顺序、分组与自定义按钮?
如何配置Jodit编辑器实现按钮分组与自定义按钮
你可以通过嵌套数组配置buttons选项来同时实现按钮分组和自定义按钮功能,这是Jodit官方推荐的简洁方案,无需复杂的UI系统操作。
1. 基础按钮分组配置
在buttons数组中,用子数组包裹同一组的按钮,组与组之间自动形成视觉分隔(也可以手动添加separator或|作为分隔符):
const editor = new Jodit('#editor', { buttons: [ // 第一组:撤销、重做 ['undo', 'redo', '|'], // 第二组:粗体、斜体、下划线 ['bold', 'italic', 'underline', '|'], // 第三组:其他默认按钮 ['align', 'list', 'link'] ] });
2. 添加自定义按钮到分组
你可以直接在分组的子数组中插入自定义按钮对象,同时保留分组结构:
const editor = new Jodit('#editor', { buttons: [ ['undo', 'redo', '|'], ['bold', 'italic', 'underline', '|'], // 自定义按钮所在分组 [ { name: 'customBtn', text: '我的按钮', iconURL: 'path/to/icon.png', // 可选:自定义图标 exec: (editor) => { // 自定义按钮逻辑 alert('自定义按钮被点击了!'); editor.insertHTML('<p>插入自定义内容</p>'); }, tooltip: '这是一个自定义按钮' // 可选:鼠标悬停提示 }, '|' ], ['image', 'video'] ] });
3. 进阶:注册全局自定义按钮(复用场景)
如果需要在多个编辑器实例中复用自定义按钮,可以先注册全局按钮,再在buttons分组中通过名称引用:
// 注册全局自定义按钮 Jodit.plugins.add('customButtonPlugin', function(editor) { editor.registerButton('myGlobalBtn', { text: '全局按钮', exec: (editor) => { console.log('全局自定义按钮触发'); }, tooltip: '全局复用按钮' }); }); // 初始化编辑器时引用 const editor = new Jodit('#editor', { buttons: [ ['undo', 'redo', '|'], ['bold', 'italic', 'underline', '|'], ['myGlobalBtn', '|'], // 引用全局注册的按钮 ['image'] ] });
关于UI系统方案的补充说明
你之前尝试的UI系统构建方式并非最优解,若仍需使用,可通过给UIButton绑定onClick事件实现自定义功能,示例:
const customUIButton = new Jodit.UI.UIButton(editor, { text: 'UI自定义按钮' }); customUIButton.on('click', () => { alert('UI按钮被点击'); }); editor.toolbar.build([ new Jodit.UI.UIGroup(editor, [customUIButton], { name: 'customGroup' }) ]);
但这种方式配置繁琐,不如直接使用buttons嵌套数组的方案高效。
内容的提问来源于stack exchange,提问作者AltenDT
相关产品推荐
相关产品推荐

