【发布时间】:2016-04-26 15:34:08
【问题描述】:
我有一个这样的 HTML 结构:
<div contenteditable="true">This is some plain, boring content.</div>
我还有这个功能,可以让我将插入符号的位置设置到 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) 添加到 div 之前,此代码可以正常工作,例如
<div contenteditable="true">
This is some <span class="fancy">plain</span>, boring content.
</div>
当这些子标签以自己的子标签结束时,事情会变得更加复杂,例如
<div contenteditable="true">
This is some <span class="fancy"><i>plain</i></span>, boring content.
</div>
基本上,发生的情况是,当我尝试将SetCaretPosition 指向高于子标签开头的索引时,setStart 会抛出一个IndexSizeError。 setStart 仅在到达第一个子标签之前有效。
我需要的是 SetCaretPosition 函数处理未知数量的这些子标签(可能还有未知数量的嵌套子标签),以便设置位置的方式与没有标签。
所以对于这两个:
<div contenteditable="true">This is some plain, boring content.</div>
还有这个:
<div contenteditable="true">
This is <u>some</u> <span class="fancy"><i>plain</i></span>, boring content.
</div>
SetCaretPosition(div, 20); 会将插入符号放在 'boring' 中的 'b' 之前。
我需要什么代码?非常感谢!
【问题讨论】:
标签: javascript jquery html