Pregunta

I'm making a little WYSIWYG for a project, and I need the ability to highlight text, click a button, and that will append a span around the selection with a class of ".highlight". The span will have a yellow background.

This is what I have so far from elsewhere on SO which is appending text instead of HTML. http://jsfiddle.net/aGzvp/

Here's the JS:

function wrap(tag) {
    var sel, range;

    if (window.getSelection) {
        sel = window.getSelection();

        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            selectedText = range.toString();
            range.deleteContents();
            range.insertNode(document.createTextNode('[' + tag + ']' + selectedText + '[/' + tag + ']'));
        }
    }
    else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        selectedText = document.selection.createRange().text + "";
        range.text = '[' + tag + ']' + selectedText + '[/' + tag + ']';
    }

}
¿Fue útil?

Solución

One option is the class highlighter module of my Rangy library. This has the advantage of working in all major browsers (including IE 6-8) and working in the general case, such as when the selection includes text that starts and ends in different elements.

If the only case you need to deal with is text inside a single text node, you can create a range from the selection and call its surroundContents() method. See the following answer for details:

https://stackoverflow.com/a/6328906/96100

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top