在有孩子的’contenteditable’div中设置Caret Position

我有这样的HTML结构:

This is some plain, boring content.

我也有这个function,允许我将插入位置设置到div中我想要的任何位置:

 // Move caret to a specific point in a DOM element function SetCaretPosition(object, pos) { // Get key data var el = object.get(0); // Strip inner object from jQuery object var range = document.createRange(); var sel = window.getSelection(); // Set the range of the DOM element range.setStart(el.childNodes[0], pos); range.collapse(true); // Set the selection point sel.removeAllRanges(); sel.addRange(range); } 

此代码完全正常,直到我开始向(span, b, i, u, strike, sup, sub)添加子标记(span, b, i, u, strike, sup, sub) ,例如

 
This is some plain, boring content.

当这些子标签最终带有自己的子标签时,事情变得更加复杂

 
This is some plain, boring content.

本质上,当我尝试将SetCaretPosition设置为高于子标记开头的索引时, setStart会抛出IndexSizeErrorsetStart仅在到达第一个子标记之前有效。

我需要的是, SetCaretPosition函数处理未知数量的这些子标签(可能还有未知数量的嵌套子标签),以便设置位置的工作方式与没有标签时相同。

对于这两个:

 
This is some plain, boring content.

还有这个:

 
This is some plain, boring content.

SetCaretPosition(div, 20); 将插入符号放在“b”之前的“无聊”中。

我需要什么代码? 非常感谢!

所以,我遇到了同样的问题,并决定快速编写自己的例程,它递归遍历所有子节点并设置位置。 注意这是如何将DOM节点作为参数,而不是原始post所做的jquery对象

 // Move caret to a specific point in a DOM element function SetCaretPosition(el, pos){ // Loop through all child nodes for(var node of el.childNodes){ if(node.nodeType == 3){ // we have a text node if(node.length >= pos){ // finally add our range var range = document.createRange(), sel = window.getSelection(); range.setStart(node,pos); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); return -1; // we are done }else{ pos -= node.length; } }else{ pos = SetCaretPosition(node,pos); if(pos == -1){ return -1; // no need to finish the for loop } } } return pos; // needed because of recursion stuff } 

我希望这对你有所帮助!

它只适用于对象Text childNodes(0)。所以你必须制作它。这里不是那么标准的代码,而是works.Goal是(p)id(我们)将输出对象文本。如果它确实那么它可能有用。

 
dddddddddddddddddddddddddddd

dd

psss

dd

dd

text text text