Set caret position at a specific position in contenteditable div

主宰稳场 提交于 2019-12-17 18:41:21

问题


SEE BEFORE MARKING DUPLICATE/DOWNVOTING

  1. The contenteditable div will not have child elements
  2. I do not want to set the position at the end of the div
  3. I do not want a cross-browser solution, only Chrome support required
  4. Only vanilla JS, no libraries.

I have seen many many solutions. Many by Tim Down, and others. But none does work. I have seen window.getSelection, .addRange etc. but don't see how they apply here.

Here's a jsfiddle.

(Tried) Code:

var node = document.querySelector("div");
node.focus();
var caret = 10; // insert caret after the 10th character say
var range = document.createRange();
range.setStart(node, caret);
range.setEnd(node, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

回答1:


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);


来源:https://stackoverflow.com/questions/24115860/set-caret-position-at-a-specific-position-in-contenteditable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!