How to move cursor to end of contenteditable entity

前端 未结 7 1811
孤街浪徒
孤街浪徒 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:44

    The problem with contenteditable

    and is resolved when you start typing in it initially. One workaround for this could be triggering a focus event on your div element and on that function, clear, and refill what was already in the div element. This way the problem is resolved and finally you can place the cursor at the end using range and selection. Worked for me.

      moveCursorToEnd(e : any) {
        let placeholderText = e.target.innerText;
        e.target.innerText = '';
        e.target.innerText = placeholderText;
    
        if(e.target.innerText && document.createRange)
        {
          let range = document.createRange();
          let selection = window.getSelection();
          range.selectNodeContents(e.target);
          range.setStart(e.target.firstChild,e.target.innerText.length);
          range.setEnd(e.target.firstChild,e.target.innerText.length);
          selection.removeAllRanges();
          selection.addRange(range);
        }
      }
    

    In HTML code:

提交回复
热议问题