如何在CKEditor选择字体后触发回调函数?已试onchange插件无效
Got it, let's fix this—you want to run a specific function whenever someone picks a font in CKEditor, and the onchange plugin isn't doing the trick. The issue with that plugin is it’s built to detect general content changes, not targeted toolbar actions like font selection. Here are two reliable ways to hook into the font picker event:
Method 1: Listen for the Font Command Execution
CKEditor uses commands to handle toolbar actions, and font selection is controlled by the font command (or fontName in some older versions). You can listen for when this command runs and fire your method:
CKEDITOR.replace('your-editor-id', { // Your existing editor config goes here on: { instanceReady: function(evt) { const editor = evt.editor; // Listen for any command being executed editor.on('command', function(commandEvt) { // Check if the command is the font selector if (commandEvt.data.name === 'font') { // Get the selected font value (optional) const selectedFont = editor.getCommand('font').value; // Call your custom method here yourCustomFunction(selectedFont); } }); } } });
Pro tip: If font doesn’t work, check your editor’s command list by running console.log(editor.commands) in your browser dev tools—look for a command related to font names.
Method 2: Hook Directly into the Font Dropdown’s Change Event
You can also target the actual dropdown element in the toolbar and listen for its change event:
CKEDITOR.replace('your-editor-id', { on: { instanceReady: function(evt) { const editor = evt.editor; // Grab the font dropdown UI element const fontDropdown = editor.ui.get('font').element; if (fontDropdown) { // Listen for when the dropdown selection changes fontDropdown.on('change', function() { const selectedFont = this.getValue(); yourCustomFunction(selectedFont); }); } } } });
Key Notes
- Make sure
yourCustomFunctionis accessible in the same scope as your CKEditor initialization code. - If you’re using a custom font plugin instead of the default one, adjust the command name or UI element ID to match your setup.
- Both methods work with CKEditor 4 (since you mentioned the onchange addon, which is for CKEditor 4).
内容的提问来源于stack exchange,提问作者rj487

