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

后端 未结 10 1513
被撕碎了的回忆
被撕碎了的回忆 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:35

    function set_mouse() {
      var as = document.getElementById("editable");
      el = as.childNodes[1].childNodes[0]; //goal is to get ('we') id to write (object Text) because it work only in object text
      var range = document.createRange();
      var sel = window.getSelection();
      range.setStart(el, 1);
      range.collapse(true);
      sel.removeAllRanges();
      sel.addRange(range);
    
      document.getElementById("we").innerHTML = el; // see out put of we id
    }
    ffffdffffdffffdffffdffffdffffdffffdffffdffffdd

    dd

    psss

    dd

    dd

    text text text

    It is very hard set caret in proper position when you have advance element like (p) (span) etc. The goal is to get (object text):

    ffffdffffdffffdffffdffffdffffdffffdffffdffffdd

    dd

    psss

    dd

    dd

    text text text

提交回复
热议问题