Enable CKEditor toolbar button only with valid text selection?

前端 未结 3 1642
醉梦人生
醉梦人生 2021-01-21 13:04

I\'m working on a CKEditor plugin for annotating text and adding margin comments, but I\'d like some of my custom toolbar buttons to be enabled only when the user has already se

3条回答
  •  一向
    一向 (楼主)
    2021-01-21 13:28

    Here is the code required to answer exactly the question using the refresh method as suggested by Gyum Fox.
    I mention that to make it work, contextSensitive has to be set to 1.

    editor.addCommand( 'myCommand', {
        exec: function( editor ) {
            // Custom logic of the command
        },
        refresh: function( editor ) {
            var editable = editor.editable();
            range = editable.getDocument().getSelection().getRanges()[ 0 ]; // We assume only one range.
            commandState = ( range && !range.collapsed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
            this.setState( commandState );
        },
        contextSensitive: 1
    });
    

    EDIT: I noticed some refresh issues on my side. So, because of that, I'd go for the Marek Lewandowski answer.

提交回复
热议问题