Insert html tags around selected text in NicEdit

2019-09-05 23:50发布

问题:

I am looking for a way to insert HTML tags around text marked in NicEdit, so that I can, for example, indent the text and make it green.

I want to do this by inserting < pre > tags around the marked text with a css class of my choice(which does the formating of the text, makes it green etc).

The code for my button look as follows:

var customButtonOptions = {
buttons : {
    'code' : {name : __('Mark text as code'), 
                type : 'nicEditorCodeButton'}} , 
                iconFiles : {'code' : '../save.gif'}

                };


var nicEditorCodeButton = nicEditorButton.extend({
mouseClick : function() {

    alert('The code button has been clicked ');
}
});

nicEditors.registerPlugin(nicPlugin,customButtonOptions);

Currently I only have an alert in the function to be sure that it works, but I need help with a function that places the < pre > tags around the text I have currently marked. So not all the text in the textarea.

Or at least a way of putting the marked text into a variable.

回答1:

This solution works for me, to set marked text as code. I hope it will work for you.

if(cmd=='code'){
        if(document.getSelection().anchorNode.data)
        {
            var a = document.getSelection().anchorOffset;
            var b = document.getSelection().focusOffset;
            var str = document.getSelection().anchorNode.data.substring(a,b);
        }
        else str = 'insert code';
        var str1 = '<div class="code">'+str+'</div>';
        function replaceSelectedText(replacementText) {
            var sel, range;
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    range.deleteContents();
                    document.execCommand('insertHTML',false,replacementText);
                }
            }
        }
        replaceSelectedText(str1);
}