Adding tags to selection

2019-09-19 01:59发布

问题:

I am using this Javascript to effect the following changes in my selected text:

    function formatText(el,tag){
var selectedText = document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
if (selectedText == "")
{return false}
var newText='"#28'+tag+'"'+selectedText+'"#28'+tag+'"';
if(document.selection){    //IE
document.selection.createRange().text=newText;
}
else{   //Moz
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
}
}

However, i want the new tags to only be visible in another textarea not the one where I actually do the selecting. In this case I have 2 Text areas, one is called "message_text" the other is called "message" ... I iwll input and select text in "message_text" but any changes made to the selection must only reflect in the "message" text area.

At present I have tried this:

<button type="button" value="D" onclick="formatText(message,'D')" class="blue">D</button>

But this only works if I have selected anytnin in the "message" text area.

Thanks

回答1:

You have to extend the javascript code:

function formatText(el_from, el_to, tag) {
    var selectedText = document.selection ? document.selection.createRange().text : el_from.value.substring(el_from.selectionStart, el_from.selectionEnd);// IE:Moz

    if (selectedText == "") {
        return false;
    }

    var start_index = el_to.value.indexOf(selectedText);
    var sel_t_len = selectedText.length;
    var copy_selText = el_to.substring(start_index, sel_t_len);

    var newText='"#28'+tag+'"'+copy_selText+'"#28'+tag+'"';

    el_to.value = el_to.value.substring(0, start_index) + newText + el_to.value.substring(sel_t_len, el_to.value.length);
}

Then You can call it like this:

<button type="button" value="D" onclick="formatText(document.getElementById('message_text'), document.getElementById('message'),'D')" class="blue">D</button>

PS: I'm not sure about document.getElementById - haven't used it for years since using jQuery... You should convert to jQuery, too... You would not noeed to solve JS for IE or FF or Chrome, etc - jQuery handles this by itself...

EDIT : OK, I did a little customization and it should fit to Your needs...