简体   繁体   中英

How to set the caret position in a contenteditable div in Firefox and old IE versions

I am trying to set the caret position in a contenteditable div. Here is code that works in modern IE, Chrome and Safari, but does not work in Firefox 36.0.4 or old IE versions (9 or less). For this answer it is safe to assume that the contenteditable div contains only text (ie no child elements other than a single text node).

Please tell me how to fix this, especially for Firefox.

Thank you.

HTML:

<div contenteditable id="d">12345</div>
<div contenteditable id="log"></div>

JavaScript:

function moveCaret(d, position) {
    d.focus(); // This is included because in my application the div is already focused by the time the caret must be moved.
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.setStart(d.childNodes[0], position);
        range.setEnd(d.childNodes[0], position);
        sel.addRange(range);
        d.focus();
     } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(d);
        textRange.select();
        d.focus();
    }
}

try {
    var position = 0;
    var d = document.getElementById("d");
    moveCaret(d, 3);
}catch(e) {
    document.getElementById("log").innerHTML += e.toString();
}

http://jsfiddle.net/bk7ade2r/

问题似乎是firefox无法将content()放在可编辑的div上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM