javascript - Set caret position in contenteditable div layer in Chromewebkit - Stack Overflow

I'm trying to set the caret position in a contenteditable div layer, and after a bit of searching

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.

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.

Share Improve this question edited Mar 16, 2022 at 16:47 General Grievance 5,04338 gold badges37 silver badges56 bronze badges asked Apr 13, 2010 at 22:33 AlexAlex 1451 gold badge2 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745498248a4630292.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信