我创建了一个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'
});
}
});
答案 0 :(得分:1)
最后,使用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'
});
}
});