开发者

Javascript set caret position in a ContentEditable div

开发者 https://www.devze.com 2023-03-19 15:37 出处:网络
I have a div with contented开发者_如何学JAVAitable set. This div contains an inner div like so:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消