Get contentEditable caret index position

后端 未结 10 716
暗喜
暗喜 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:38

    window.getSelection - vs - document.selection

    This one works for me:

    function getCaretCharOffset(element) {
      var caretOffset = 0;
    
      if (window.getSelection) {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length;
      } 
    
      else if (document.selection && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
      }
    
      return caretOffset;
    }
    
    
    // Demo:
    var elm = document.querySelector('[contenteditable]');
    elm.addEventListener('click', printCaretPosition)
    elm.addEventListener('keydown', printCaretPosition)
    
    function printCaretPosition(){
      console.log( getCaretCharOffset(elm), 'length:', this.textContent.trim().length )
    }
    some text here italic text here some other text here bold text here end of text

    The calling line depends on event type, for key event use this:

    getCaretCharOffsetInDiv(e.target) + ($(window.getSelection().getRangeAt(0).startContainer.parentNode).index());
    

    for mouse event use this:

    getCaretCharOffsetInDiv(e.target.parentElement) + ($(e.target).index())
    

    on these two cases I take care for break lines by adding the target index

提交回复
热议问题