TinyMCE技术问询:获取编辑器首行字体族及初始化匹配工具栏字体
1. How to Get the First Line's Font-Family in TinyMCE
To retrieve the font-family of the first line of text in your TinyMCE editor, you can use the editor's DOM API combined with the browser's computed style functionality. Here's a straightforward approach:
- Grab a reference to your editor instance (using
tinymce.get('your-editor-id')). - Access the editor's body content and target the first block-level element (like
<p>,<div>, or heading tags—these are the standard containers for lines in TinyMCE). - Use
window.getComputedStyle()to get the actual applied font-family (this accounts for inherited styles too).
Here's a working code snippet:
const editor = tinymce.get('your-editor-id'); if (editor) { const body = editor.getBody(); const firstBlock = body.firstElementChild; if (firstBlock) { const computedStyle = window.getComputedStyle(firstBlock); // Clean up quotes from the font family string const fontFamily = computedStyle.fontFamily.replace(/['"]+/g, ''); console.log('First line font family:', fontFamily); } }
If your first line is wrapped in an inline element (like <span>) inside a block, adjust the code to target that inline element instead—though block-level elements are the typical starting point.
2. Set Toolbar's fontName to First Line's Font on Initialization
To fix the issue where the toolbar's fontName dropdown defaults to 'Arial' instead of matching the first line's font, you can hook into the editor's init event. After the editor loads its saved content, retrieve the first line's font-family and update the dropdown's value manually.
Here's how to implement this in your TinyMCE configuration:
tinymce.init({ selector: '#your-editor-id', // Add your other editor config options here... setup: function(editor) { editor.on('init', function() { // Small timeout to ensure content is fully rendered before checking setTimeout(() => { const body = editor.getBody(); const firstBlock = body.firstElementChild; if (firstBlock) { const computedStyle = window.getComputedStyle(firstBlock); const fontFamily = computedStyle.fontFamily.replace(/['"]+/g, ''); // Update the fontName dropdown to match the first line's font const fontControl = editor.controlManager.get('fontName'); if (fontControl) { fontControl.setValue(fontFamily); } } }, 100); }); } });
Key Notes:
- The
setTimeoutis a safe guard to avoid race conditions where the content might not be fully loaded when we check the first line. Depending on your setup, you might be able to remove it, but it’s a low-risk addition. - If the first line inherits its font from a parent element (no explicit font set), the computed value will be the default font for your editor/page—exactly what you want to show in the dropdown.
- This overrides the initial 'Arial' default by pulling the actual content font immediately after initialization, so the toolbar matches the content from the start.
内容的提问来源于stack exchange,提问作者inertia

