簡體   English   中英

在CKEditor中獲取選擇的樣式值

[英]Get style value of selection in CKEditor

我正在使用CKEditor的編輯功能,但是使用我自己的ui控件調用CKEditor的api來執行其命令。 例如,

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

editor.applyStyle(style);

設置所選文本的字體大小。

問題是我需要一種方法來了解當前所選文本的狀態,以便我可以相應地更新控件。 它大膽嗎? 然后粗體按鈕應處於激活狀態,單擊它應刪除粗體,而不是嘗試再次添加。

有沒有辦法查詢CKEditor當前所選文本的某些樣式屬性? 就像tinymce.activeEditor.queryCommandValue('bold')在tinyMCE中的工作原理非常相似。

通常,創建按鈕命令式三重奏的最佳方法就像在basicstyles插件中完成的那樣

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'
} );

此代碼將處理所有內容 - 命令和按鈕狀態將根據選擇更改進行更新。 您還可以輕松獲取命令狀態:

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

但是,如果要直接查詢樣式的狀態,則可以使用style.checkActive()方法:

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

您無需為此創建命令和按鈕。

編輯

CKEditor樣式系統有其局限性。 例如,您不能在樣式中使用可變的字體大小。 這意味着要檢查當前字體大小,您需要在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' );
    }
}

現在,只需在editor#selectionChange事件監聽editor#selectionChange使用此方法即可更新控件的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM