简体   繁体   中英

Set caret position at a specific position in contenteditable div

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM