How to add CSS classes and an ID to paragraphs in CKEditor?

 ̄綄美尐妖づ 提交于 2019-11-30 20:36:45

Here you go. This code will number your paragraphs with subsequent ids and it also will append a custom class to each paragraph which hasn't been assigned yet.

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

I've gone around and done something like this (I'm using 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');
    }
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!