How to move cursor to end of contenteditable entity

前端 未结 7 1806
孤街浪徒
孤街浪徒 2020-11-22 12:12

I need to move caret to end of contenteditable node like on Gmail notes widget.

I read threads on StackOverflow, but those solutions are based on using

相关标签:
7条回答
  • 2020-11-22 12:48

    It's possible to do set cursor to the end through the range:

    setCaretToEnd(target/*: HTMLDivElement*/) {
      const range = document.createRange();
      const sel = window.getSelection();
      range.selectNodeContents(target);
      range.collapse(false);
      sel.removeAllRanges();
      sel.addRange(range);
      target.focus();
      range.detach(); // optimization
    
      // set scroll to the end if multiline
      target.scrollTop = target.scrollHeight; 
    }
    
    0 讨论(0)
提交回复
热议问题