问题描述
我将这个简单的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:
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);
IE< 9完全不同。如果你需要支持这些浏览器,你需要不同的代码。
IE < 9 works completely differently. If you need to support these browsers, you'll need different code.
jsFiddle示例:
jsFiddle example: http://jsfiddle.net/timdown/vXnCM/
这篇关于如何在contenteditable元素(div)中设置插入符号(光标)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!