如何在CKEditor中为段落添加CSS类和ID



如何在CKEditor中向文本段落添加自定义类或ID?我想从DB中加载可能的类,并在加载CKE时将它们写入任何列表中。身份证只需当场补办即可。类和ID将用于诸如将一段文本标记为脚注或标题之类的事情。


需要明确的是,我不想使用下拉框更改文本的可见样式,我想添加CSS类,这些类可以在元素保存后用于对其进行样式设置,具体取决于它的使用位置。

开始吧。这段代码会用后续的id给你的段落编号,还会给每个还没有分配的段落附加一个自定义类。

var idCounter = 0,
    pClass = 'myCustomClass',
    pClassRegexp = new RegExp( pClass, 'g' );
CKEDITOR.replace( 'editor1', {
    on: {
        instanceReady: function() {
            this.dataProcessor.htmlFilter.addRules({
                elements: {
                    p: function( element ) {
                        // If there's no class, assing the custom one:
                        if ( !element.attributes.class )
                            element.attributes.class = pClass;
                        // It there's some other class, append the custom one:
                        else if ( !element.attributes.class.match( pClassRegexp ) )
                            element.attributes.class += ' ' + pClass;
                        // Add the subsequent id:
                        if ( !element.attributes.id )
                            element.attributes.id = 'paragraph_' + ++idCounter;
                    }
                }
            });
        }
    }
});

我到处都做了这样的事情(我使用的是CKeditor 4.4.7):

editor.addCommand('colSm1', {
    exec: function (editor) {
    var $element = editor.elementPath().block;
    if ($element.getAttribute('class') == null) {
        $element.addClass('col-sm-1');
    }
});

最新更新