Get style value for selection in CKEditor

I use the editing capabilities of CKEditor, but with my own ui controls that invoke CKEditor api to execute their commands. For instance.

var style = new CKEDITOR.style({ element: 'span', attributes: { 'style': 'font-size: 20px' } }); editor.applyStyle(style); 

to set the font size for the selected text.

The problem is that I need a way to find out the status of the currently selected text so that I can update the controls accordingly. Is it bold? Then the bold button should be in an active state, and clicking on it should remove the courage, and not try to add it again.

Is there a way to query CKEditor for certain style attributes of the current selected text? Very similar to how tinymce.activeEditor.queryCommandValue('bold') works in tinyMCE.

+5
source share
1 answer

As a rule, the best way to create a trio in the style of a command button is similar to how it is done in the basicstyles plugin:

 var style = new CKEDITOR.style( { ... } ); editor.attachStyleStateChange( style, function( state ) { !editor.readOnly && editor.getCommand( 'commandName' ).setState( state ); } ); editor.addCommand( 'commandName', new CKEDITOR.styleCommand( style ) ); editor.ui.addButton( 'buttonName', { label: 'buttonLabel', command: 'commandName' } ); 

This code will take care of everything - the command and button state will be updated in accordance with the selection changes. You can also easily get the status of a command:

 editor.getCommand( 'commandName' ).state; // Returns on of CKEDITOR.TRISTATE_*. 

However, if you want to directly query the state of the style, you can use the style.checkActive() method:

 style.checkActive( editor.elementPath(), editor ); 

You do not need to create commands and buttons for this.

Edit

The CKEditor style system has its limitations. For example, you cannot have a variable font size in a style. This means that to check the current font size you need to do a quick search in the DOM:

 function getFontSize() { var span = editor.elementPath().contains( isFontSizeSpan ); return span ? span.getStyle( 'font-size' ) : null; function isFontSizeSpan( el ) { return el.is( 'span' ) && el.getStyle( 'font-size' ); } } 

Now just use this method in the editor#selectionChange event listener to update the reference value.

+1
source

Source: https://habr.com/ru/post/1208120/


All Articles