给定一个可满足内容的Div,如何将光标设置到特定位置

Given a contentEditable Div how to set the cursor to a specific position?

本文关键字:光标 设置 位置 定位 Div 一个 可满足      更新时间:2023-09-26

给定一个像这样的contentitablediv:

<div contenteditable="true">Here is some text, hello world.</div>

如何将光标设置在位置6,就在s后面?

我一直在尝试使用:

savedRange = window.getSelection().getRangeAt(0);

然后像这样修改值:

savedRange.startOffset = 6
savedRange.endOffset = 6

但是这并没有更新saverange

有什么想法我怎么能得到光标/插入符在div?由于

位置7。无论如何,这里是如何,假设你给你的可编辑的<div>的id为"myDiv"。注意,这在IE中不起作用;9、有完全不同的范围和选择API。

if (window.getSelection) {
    var sel = window.getSelection();
    var textNode = document.getElementById("myDiv").firstChild;
    var range = document.createRange();
    range.setStart(textNode, 7);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}