How to set the caret (cursor) position in a contenteditable element (div)?(如何在 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/
这篇关于如何在 contenteditable 元素(div)中设置插入符号(光标)位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 contenteditable 元素(div)中设置插入符号(光标)位置?


- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01