简体   繁体   中英

Inserting caret after an inserted node

So I have a method that takes a tag and wraps the selected text in that tag.

function wrap(tag) 
{               
    var sel, range;
    if (window.getSelection)
    {
        sel = window.getSelection();
        if (sel.rangeCount)
        {
            range = sel.getRangeAt(0);
            var selectedText = range.toString();
            range.deleteContents();
            range.insertNode(document.createTextNode('['+tag+']'+selectedText+'[/'+tag+']'));                            
        }
    } 
}

This issue with this however, is after it's done wrapping the text and inserting the node the caret (where they are typing) is placed BEFORE the inserted text.

Is there such way to insert the text and have the caret remain at the end of it?

Please note i'd prefer if this could be done without the use of jQuery or any other library. I only need it to work in webkit (Safari).

You can use the range.setStartAfter and range.setEndAfter methods to set the start and end points to the point directly after your new node. I setup a jsfiddle example here: http://jsfiddle.net/phil_mcc/tM3mA/

//move the caret
range.setStartAfter(newNode);
range.setEndAfter(newNode); 
sel.removeAllRanges();
sel.addRange(range);

do this after inserting the node to the range range.collapse(false); this will change position of selection range to the end of the range, so my guess is it should set the cursor at end position

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