簡體   English   中英

如何在Firefox和舊版IE中的contenteditable div中設置插入符位置

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

我正在嘗試在contenteditable div中設置插入符號位置。 這是在現代IE,Chrome和Safari中有效的代碼,但在Firefox 36.0.4或舊IE版本(9或更低版本)中無效。 對於此答案,可以安全地假定contenteditable div僅包含文本(即,除了單個文本節點外,沒有其他子元素)。

請告訴我如何解決此問題,尤其是對於Firefox。

謝謝。

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上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM