Set caret position right after the inserted element in a contentEditable div

前端 未结 3 582
再見小時候
再見小時候 2020-11-29 01:51

I\'m inserting an element into a contentEditable div but the browser sets the position of the cursor before the inserted element. Is it possible to set the cursor right afte

3条回答
  •  既然无缘
    2020-11-29 02:03

    If you're inserting an empty div, p or span, I believe there needs to be "something" inside the newly created element for the range to grab onto -- and in order to put the caret inside there.

    Here's my hack that seems to work OK in Chrome. The idea is simply to put a temporary string inside the element, then remove it once the caret is in there.

    // Get the selection and range
    var idoc = document; // (In my case it's an iframe document)
    var sel = idoc.getSelection();
    var range = sel.getRangeAt(0);
    
    // Create a node to insert
    var p = idoc.createElement("p"); // Could be a div, span or whatever
    
    // Add "something" to the node.
    var temp = idoc.createTextNode("anything");
    p.appendChild(temp);
    // -- or --
    //p.innerHTML = "anything";
    
    // Do the magic (what rangy showed above)
    range.collapse(false);
    range.insertNode( p );
    range = range.cloneRange();
    range.selectNodeContents(p);
    range.collapse(false);
    sel.removeAllRanges();
    sel.addRange(range);
    
    // Clear the non
    p.removeChild(p.firstChild);
    // -- or --
    //p.innerHTML = "";
    

提交回复
热议问题