Set caret position in contenteditable div layer in Chrome/webkit

本秂侑毒 提交于 2020-01-03 01:40:35

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/2633668/set-caret-position-in-contenteditable-div-layer-in-chrome-webkit

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