简体   繁体   中英

Insert text before and after the selected text in javascript

I want to put some specified text (where possible/any editable field) before and after any selected text in an HTML document. document.getSelection() or document.selection.createRange().text returns only the text itself not the position. Is there anyway to replace the selected text? Anyway to insert specific text before and after selcted text anywhere in the document?

Try this:

var r = document.selection.createRange();

r.text = "before" + r.text;
r.text += "after";

Here's a cross-browser function to do this, which works in all major browsers and caters for the vastly different way IE does this compared to other browsers.

Live example: http://jsfiddle.net/timdown/UWExN/64/

function insertHtmlAtSelectionEnd(html, isBefore) {
    var sel, range, node;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = window.getSelection().getRangeAt(0);
            range.collapse(isBefore);

            // Range.createContextualFragment() would be useful here but was
            // until recently non-standard and not supported in all browsers
            // (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.collapse(isBefore);
        range.pasteHTML(html);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM