0

我创建了一个 ckeditor 插件,将选定的文本包装到一个跨度中。我想知道当我将此插件应用于先前已包装到跨度中的文本时,如何解开所选内容。

CKEDITOR.plugins.add('important', {
    // Register the icons. They must match command names.
    //trick to get a 16*16 icon : http://www.favicomatic.com
    icons: 'important',
    init: function (editor) {
        editor.addCommand('important', {
            // Define the function that will be fired when the command is executed.
            exec: function (editor) {
                var selected_text = editor.getSelection().getSelectedText();
                console.log(editor.getSelection()) ;
                var newElement = new CKEDITOR.dom.element("span");
                newElement.setAttributes({class: 'important'});
                newElement.setText(selected_text);
                editor.insertElement(newElement);
                //how to unwrap the selected text ?


        });

        // Create the toolbar button that executes the above command.
        editor.ui.addButton('important', {
            label: 'Set this as important',
            command: 'important',
            toolbar: 'insert'
        });
    }
});
4

1 回答 1

2

最后,使用 editor.getSelection().getStartElement(),我可以检查起始元素是否已经被类包装并在必要时将其删除。

CKEDITOR.plugins.add('important', {
    //trick to get a 16*16 icon : http://www.favicomatic.com
    icons: 'important',
    init: function (editor) {
        var className = 'important';
        editor.addCommand('important', {
            // Define the function that will be fired when the command is executed.
            exec: function (editor) {
                var editorSelection = editor.getSelection();
                var selected_text = editorSelection.getSelectedText();
                var startElement = editorSelection.getStartElement();

                //if the element has already been wrapped, let's UNwrap it
                if (className === startElement.$.className) {
                    var html = startElement.$.innerHTML;
                    editor.getSelection().getStartElement().remove();
                    editor.insertHtml(html);
                } else {
                    //if the element has NOT already been wrapped, let's wrap it
                    var newElement = new CKEDITOR.dom.element("span");
                    newElement.setAttributes({class: 'important'});
                    newElement.setText(selected_text);
                    editor.insertElement(newElement);
                }
            }
        });

        // Create the toolbar button that executes the above command.
        editor.ui.addButton('important', {
            label: 'Set this as important',
            command: 'important',
            toolbar: 'insert'
        });
    }
});
于 2015-12-22T17:28:54.630 回答