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

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

      const el = document.getElementById("editable");
      el.focus()
      let char = 1, sel; // character at which to place caret
    
      if (document.selection) {
        sel = document.selection.createRange();
        sel.moveStart('character', char);
        sel.select();
      }
      else {
        sel = window.getSelection();
        sel.collapse(el.lastChild, char);
      }
    

提交回复
热议问题