如何为EditorJS所有工具添加自定义Tune或设置为默认Tune
在EditorJS中为所有工具全局添加自定义Tune的解决方案
EditorJS 本身没有提供直接设置全局默认 Tune 的配置项,你需要通过工具扩展的方式,给每个目标工具(paragraph、header、list)绑定自定义 Tune。下面是两种可行的实现方案:
方案一:逐个工具手动配置 Tune
针对每个用到的官方工具,在其配置中显式添加自定义的 BackgroundColorTune:
// 先定义你的自定义BackgroundColorTune类 class BackgroundColorTune { static get isTune() { return true; } constructor({ api, data, block }) { this.api = api; this.data = data || { color: '#ffffff' }; this.block = block; this.wrapper = null; } render() { this.wrapper = document.createElement('div'); this.wrapper.innerHTML = `<input type="color" value="${this.data.color}" style="width: 40px; height: 40px;">`; this.wrapper.querySelector('input').addEventListener('change', (e) => { this.data.color = e.target.value; this.block.holder.style.backgroundColor = this.data.color; this.api.toolbar.update(); }); return this.wrapper; } save() { return this.data; } wrap(blockContent) { blockContent.style.backgroundColor = this.data.color; return blockContent; } } // 初始化EditorJS时,给每个工具配置tunes const editor = new EditorJS({ holder: 'editor-container', tools: { paragraph: { class: Paragraph, tunes: [BackgroundColorTune] // 为段落工具添加自定义Tune }, header: { class: Header, tunes: [BackgroundColorTune] // 为标题工具添加自定义Tune }, list: { class: List, tunes: [BackgroundColorTune] // 为列表工具添加自定义Tune } } });
方案二:批量包装工具(减少重复代码)
如果需要给多个工具添加同一个 Tune,可以写一个工具包装函数,批量处理目标工具:
// 定义工具包装高阶函数 const withBackgroundColorTune = (OriginalTool) => { return class extends OriginalTool { constructor(options) { super(options); // 合并原工具的tunes(如果有的话)与自定义Tune this.tunes = [...(this.tunes || []), new BackgroundColorTune({ api: options.api, data: options.data?.tunes?.backgroundColor, block: options.block })]; } save(blockContent) { const originalData = super.save(blockContent); // 保存自定义Tune的数据 const bgTune = this.tunes.find(t => t instanceof BackgroundColorTune); return { ...originalData, tunes: { ...originalData.tunes, backgroundColor: bgTune?.save() } }; } }; }; // 包装需要用到的工具 const ParagraphWithTune = withBackgroundColorTune(Paragraph); const HeaderWithTune = withBackgroundColorTune(Header); const ListWithTune = withBackgroundColorTune(List); // 初始化EditorJS时使用包装后的工具 const editor = new EditorJS({ holder: 'editor-container', tools: { paragraph: { class: ParagraphWithTune }, header: { class: HeaderWithTune }, list: { class: ListWithTune } } });
注意事项
- 确保目标工具本身支持 Tune 机制:官方的 paragraph、header、list 工具都原生支持,自定义工具需要确保实现了
tunes相关逻辑。 - 保存数据时,要正确合并原工具数据与 Tune 数据,避免丢失配置。
- 如果工具本身已有其他 Tune,使用方案二时要注意合并数组,不要直接覆盖原
tunes。
内容的提问来源于stack exchange,提问作者Karan S
相关产品推荐
相关产品推荐

