Set caret position at a specific position in contenteditable div

后端 未结 1 1936
傲寒
傲寒 2020-12-05 19:31

SEE BEFORE MARKING DUPLICATE/DOWNVOTING

  1. The contenteditable div will not have child elements
  2. I do not want to set th
相关标签:
1条回答
  • 2020-12-05 20:01

    You need to position the caret within the text node inside your element, not the element itself. Assuming your HTML looks something like <div contenteditable="true">Some text</div>, using the firstChild property of the element will get the text node.

    Updated jsFiddle:

    http://jsfiddle.net/xgz6L/8/

    Code:

    var node = document.querySelector("div");
    node.focus();
    var textNode = node.firstChild;
    var caret = 10; // insert caret after the 10th character say
    var range = document.createRange();
    range.setStart(textNode, caret);
    range.setEnd(textNode, caret);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    
    0 讨论(0)
提交回复
热议问题