如何为TinyMCE配置基于CSS类的颜色面板?
实现TinyMCE基于Tailwind CSS类的颜色面板
我刚好做过类似的需求,完全可以实现用Tailwind的text-*类代替内联颜色样式,下面是具体的解决方案:
核心思路
不用TinyMCE默认的color_map(它会生成内联style),而是通过自定义格式+自定义工具栏按钮来绑定Tailwind类,同时加载Tailwind CSS让编辑器预览同步样式。
完整配置示例
tinymce.init({ selector: '#editor', // 加载Tailwind CSS,确保编辑器内能实时预览颜色 content_css: 'https://cdn.tailwindcss.com', // 定义每个Tailwind文本颜色对应的格式规则 formats: { text_primary_500: { inline: 'span', classes: 'text-primary-500', remove: 'all' // 应用时移除其他同类格式,避免冲突 }, text_secondary_400: { inline: 'span', classes: 'text-secondary-400', remove: 'all' }, text_gray_900: { inline: 'span', classes: 'text-gray-900', remove: 'all' }, text_white: { inline: 'span', classes: 'text-white', remove: 'all' } }, // 把自定义颜色按钮加到工具栏 toolbar: 'custom_text_colors', setup: function(editor) { // 创建自定义颜色下拉菜单按钮 editor.ui.registry.addMenuButton('custom_text_colors', { text: '文本颜色', fetch: function(callback) { const colorItems = [ { type: 'menuitem', text: 'Primary 500', onAction: () => { // 先移除所有已有的text-*类,再应用新类 editor.formatter.remove('text_primary_500 text_secondary_400 text_gray_900 text_white'); editor.formatter.apply('text_primary_500'); } }, { type: 'menuitem', text: 'Secondary 400', onAction: () => { editor.formatter.remove('text_primary_500 text_secondary_400 text_gray_900 text_white'); editor.formatter.apply('text_secondary_400'); } }, { type: 'menuitem', text: 'Gray 900', onAction: () => { editor.formatter.remove('text_primary_500 text_secondary_400 text_gray_900 text_white'); editor.formatter.apply('text_gray_900'); } }, { type: 'menuitem', text: 'White', onAction: () => { editor.formatter.remove('text_primary_500 text_secondary_400 text_gray_900 text_white'); editor.formatter.apply('text_white'); } } ]; callback(colorItems); } }); // 可选:监听节点变化,高亮当前激活的颜色按钮 editor.on('NodeChange', (e) => { const activeClasses = e.element.className.split(' '); const hasTextColorClass = activeClasses.some(cls => cls.startsWith('text-')); editor.ui.registry.toggleButton('custom_text_colors', { active: hasTextColorClass }); }); } });
关键细节说明
自定义格式:
inline: 'span'会生成<span class="text-primary-500">,适合给选中的部分文本着色;如果需要给整个段落加类,把inline改成block并指定block: 'p',就能生成<p class="text-primary-500">。remove: 'all'确保每次应用新类时,会移除之前的同类颜色类,避免样式冲突。
预览同步:
通过content_css加载Tailwind的CSS文件(可以是CDN或本地编译后的文件),编辑器内的内容会直接使用这些类,所以当你修改Tailwind的text-*类颜色值时,编辑器预览会自动同步更新。用户体验优化:
NodeChange事件监听可以让工具栏按钮显示当前是否有颜色类激活,用户能直观看到当前文本的颜色状态。
这样配置后,生成的代码就是你想要的类名形式,完全脱离硬编码的颜色值,完美适配Tailwind的工作流~
内容的提问来源于stack exchange,提问作者Matěj Černý
相关产品推荐
相关产品推荐

