Get contentEditable caret index position

后端 未结 10 818
暗喜
暗喜 2020-11-22 05:48

I\'m finding tons of good, crossbrowser anwers on how to SET the cursor or caret index position in a contentEditable element, but none on how to GET or find its

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:29

    Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:

    function cursor_position() {
        var sel = document.getSelection();
        sel.modify("extend", "backward", "paragraphboundary");
        var pos = sel.toString().length;
        if(sel.anchorNode != undefined) sel.collapseToEnd();
    
        return pos;
    }
    
    // Demo:
    var elm = document.querySelector('[contenteditable]');
    elm.addEventListener('click', printCaretPosition)
    elm.addEventListener('keydown', printCaretPosition)
    
    function printCaretPosition(){
      console.log( cursor_position(), 'length:', this.textContent.trim().length )
    }
    some text here italic text here some other text here bold text here end of text

    It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary to documentboundary or whatever granularity for your case. Check out the API for more details. Cheers! :)

提交回复
热议问题