简体   繁体   中英

Set caret position in contenteditable div layer in Chrome/webkit

I'm trying to set the caret position in a contenteditable div layer, and after a bit of searching the web and experimenting I got it to work in firefox using this:

function set(element,position){
    element.focus();
    var range= window.getSelection().getRangeAt(0);
    range.setStart(element.firstChild,position);
    range.setEnd(element.firstChild,position);
}

[...]

set(document.getElementById("test"),3);

But in Chrome/webkit it selects all of the content in the div. Is this a bug with webkit or am I doing something wrong?
Thank you in advance.

The offset of a Range boundary within a node is only a character offset if the node is a text node. If the node is an element, the offset is the number of child nodes prior to the boundary.

For example, if you have HTML

<div id="myDiv">One <b>two</b> three</div>

... and you create a Range as follows:

var range = document.createRange();
var myDiv = document.getElementById("myDiv");
range.setStart(myDiv, 1);
range.setEnd(myDiv, 1);

... you'll get a Range that starts and ends immediately after the first child of the div, which is a text node:

<div id="myDiv">One |<b>two</b> three</div>

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