在Chrome / webkit中的contenteditable div层中设置插入位置 [英] Set caret position in contenteditable div layer in Chrome/webkit
问题描述
我试图在一个contenteditable的div层中设置插入位置,经过一些搜索网络和实验,我得到它的工作在firefox使用这:
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);
但是在Chrome / webkit中,它选择div中的所有内容。这是webkit的错误还是我做错了什么?
提前谢谢。
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.
推荐答案
如果节点是文本节点,则在节点内的Range边界的偏移仅仅是字符偏移。如果节点是一个元素,偏移量是边界之前的子节点数。
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.
例如,如果你有HTML
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);
...你会得到一个Range,它在div的第一个子元素后立即开始和结束,其是文本节点:
... 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>
这篇关于在Chrome / webkit中的contenteditable div层中设置插入位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!