如何在 contenteditable 元素(div)中设置插入符号(光标)位置?

我以这个简单的 HTML 为例:

I have this simple HTML as an example:

<div id="editable" contenteditable="true">
  text text text<br>
  text text text<br>
  text text text<br>
</div>
<button id="button">focus</button>

我想要简单的东西 - 当我单击按钮时,我想将插入符号(光标)放在可编辑 div 中的特定位置.通过网络搜索,我将此 JS 附加到按钮单击,但它不起作用(FF、Chrome):

I want simple thing - when I click the button, I want to place caret(cursor) into specific place in the editable div. From searching over the web, I have this JS attached to button click, but it doesn't work (FF, Chrome):

var range = document.createRange();
var myDiv = document.getElementById("editable");
range.setStart(myDiv, 5);
range.setEnd(myDiv, 5);

是否可以像这样手动设置插入符号位置?

Is it possible to set manually caret position like this ?

推荐答案

在大多数浏览器中,您需要 范围选择 对象.您将每个选择边界指定为一个节点和该节点内的偏移量.例如,要将插入符号设置为第二行文本的第五个字符,您需要执行以下操作:

In most browsers, you need the Range and Selection objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:

function setCaret() {
    var el = document.getElementById("editable")
    var range = document.createRange()
    var sel = window.getSelection()
    
    range.setStart(el.childNodes[2], 5)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)
}

<div id="editable" contenteditable="true">
  text text text<br>text text text<br>text text text<br>
</div>

<button id="button" onclick="setCaret()">focus</button>

IE<9 的工作方式完全不同.如果您需要支持这些浏览器,则需要不同的代码.

IE < 9 works completely differently. If you need to support these browsers, you'll need different code.

jsFiddle 示例:http://jsfiddle.net/timdown/vXnCM/

jsFiddle example: http://jsfiddle.net/timdown/vXnCM/

相关文章