Insert html tags around selected text in NicEdit

喜欢而已 提交于 2019-12-14 03:19:54

问题


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


来源:https://stackoverflow.com/questions/23909404/insert-html-tags-around-selected-text-in-nicedit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!