如何为TinyMCE 5的fontsizeselect添加基于CSS类的字号选项
TinyMCE 5 自定义类字号功能实现方案
TinyMCE 5 官方未将类绑定功能内置到 fontsize_formats 配置中,可通过自定义下拉菜单 + 格式注册的方式完全还原老版本的类绑定字号效果,无需修改编辑器内核。
1. 注册自定义带类格式
通过 formats 配置项预先定义你需要的字号对应的类规则,不会生成内联样式:
tinymce.init({ selector: 'textarea#editor', // 其他基础配置保留 formats: { // 大字号对应 .big 类 big_size: { inline: 'span', classes: 'big', remove: 'all' // 切换时自动清除同类型其他格式 }, // 正常字号对应 .normal 类 normal_size: { inline: 'span', classes: 'normal', remove: 'all' }, // 小字号对应 .small 类 small_size: { inline: 'span', classes: 'small', remove: 'all' } // 可按需扩展更多格式 },
2. 自定义字号下拉按钮替换原生组件
在 setup 钩子中注册自定义工具栏按钮,替换原生的 fontsizeselect,复用原生字号图标保持视觉一致:
setup: function (editor) { // 注册自定义字号下拉按钮 editor.ui.registry.addMenuButton('custom_font_size', { icon: 'font-size', tooltip: '字号', fetch: function (callback) { // 定义下拉选项,对应之前注册的格式 const menuItems = [ { type: 'menuitem', text: '大字号', onAction: () => editor.formatter.apply('big_size') }, { type: 'menuitem', text: '正常', onAction: () => editor.formatter.apply('normal_size') }, { type: 'menuitem', text: '小字号', onAction: () => editor.formatter.apply('small_size') } ] callback(menuItems) } }) }, // 工具栏配置中替换原生字号选择器 toolbar: 'custom_font_size bold italic underline', // 其他原有按钮保留即可
3. 配置编辑器内预览样式
将类对应的样式规则写入 content_style 配置,保证编辑状态下就能看到字号效果:
content_style: ` .big { font-size: 24px; line-height: 1.6; } .normal { font-size: 16px; line-height: 1.5; } .small { font-size: 12px; line-height: 1.4; } /* 其他自定义内容样式 */ ` })
该方案最终生成的富文本只会给选中内容套上对应类名的 span 标签,无冗余内联样式,和 TinyMCE 3 的 theme_advanced_font_sizes 类配置效果完全一致。如果需要同时支持字面字号和自定义类选项,也可以在下拉选项中混合调用 editor.execCommand('FontSize', false, '18px') 触发原生字号逻辑,灵活度高于旧版本的固定配置。
内容的提问来源于stack exchange,提问作者Ric
相关产品推荐
相关产品推荐

