How to set caret(cursor) position in contenteditable element (div)?

后端 未结 10 1515
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 01:41

I have this simple HTML as an example:

text text text
text text text
text text
10条回答
  •  广开言路
    2020-11-22 02:27

    I'm writting a syntax highlighter (and basic code editor), and I needed to know how to auto-type a single quote char and move the caret back (like a lot of code editors nowadays).

    Heres a snippet of my solution, thanks to much help from this thread, the MDN docs, and a lot of moz console watching..

    //onKeyPress event
    
    if (evt.key === "\"") {
        let sel = window.getSelection();
        let offset = sel.focusOffset;
        let focus = sel.focusNode;
    
        focus.textContent += "\""; //setting div's innerText directly creates new
        //nodes, which invalidate our selections, so we modify the focusNode directly
    
        let range = document.createRange();
        range.selectNode(focus);
        range.setStart(focus, offset);
    
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
    }
    
    //end onKeyPress event
    

    This is in a contenteditable div element

    I leave this here as a thanks, realizing there is already an accepted answer.

提交回复
热议问题