Javascript set caret position in a ContentEditable div
I have a div with contented开发者_如何学JAVAitable
set. This div contains an inner div like so:
<div contenteditable="true" class="key">
<div class="innerKey">276</div>
</div>
The odd editable div structure comes about from the need for other functionality.
How would I go about setting the caret position to the start of the content of the inner div using javascript?
In browsers other than IE < 9, you can do this pretty simply, assuming for brevity that you added an id of "innerKey" to the inner <div>
:
var sel = window.getSelection();
var innerDiv = document.getElementById("innerKey");
var innerDivText = innerDiv.firstChild;
sel.collapse(innerDivText, 0);
jsFiddle: http://jsfiddle.net/Jaj6t/5/
If you need to support IE < 9, you can use my Rangy library to provide the cross-browser DOM Range and Selection support.
精彩评论