如何在 contenteditable 元素 (div) 中设置插入符号 (光标) 位置? [英] How to set the caret (cursor) position in a contenteditable element (div)?
问题描述
我以这个简单的 HTML 为例:
文本 文本 文本
文本 文本 文本
文本 文本 文本
<button id="button">focus</button>
我想要简单的事情 - 当我单击按钮时,我想将插入符号(光标)放置到可编辑 div 中的特定位置.通过网络搜索,我将此 JS 附加到按钮单击,但它不起作用(FF,Chrome):
var range = document.createRange();var myDiv = document.getElementById("editable");range.setStart(myDiv, 5);range.setEnd(myDiv, 5);
是否可以像这样手动设置插入符号位置?
在大多数浏览器中,您需要 Range
和 Selection
对象.您将每个选择边界指定为一个节点和该节点内的偏移量.例如,要将插入符号设置为第二行文本的第五个字符,您需要执行以下操作:
function setCaret() {var el = document.getElementById("editable")var range = document.createRange()var sel = window.getSelection()range.setStart(el.childNodes[2], 5)range.collapse(真)sel.removeAllRanges()sel.addRange(范围)}
text text text
text text text
text text text
<button id="button" onclick="setCaret()">focus</button>
IE<9 的工作方式完全不同.如果您需要支持这些浏览器,则需要不同的代码.
jsFiddle 示例:http://jsfiddle.net/timdown/vXnCM/
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>
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 works completely differently. If you need to support these browsers, you'll need different code.
jsFiddle example: http://jsfiddle.net/timdown/vXnCM/
这篇关于如何在 contenteditable 元素 (div) 中设置插入符号 (光标) 位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!