我将如何修改这个(How to set caret(cursor) position in contenteditable element (div)?),以便它接受数字索引和元素并将光标位置设置为该索引?
例如:如果我有段落:
<p contenteditable="true">This is a paragraph.</p>
我打电话给:
setCaret($(this).get(0), 3)
光标会像这样移动到索引 3:
Thi|s is a paragraph.
我有这个,但没有运气:
function setCaret(contentEditableElement, index)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.setStart(contentEditableElement,index);
range.collapse(true);
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}