简体   繁体   English

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

[英]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. 我正在尝试在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). 这是在现代IE,Chrome和Safari中有效的代码,但在Firefox 36.0.4或旧IE版本(9或更低版本)中无效。 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). 对于此答案,可以安全地假定contenteditable div仅包含文本(即,除了单个文本节点外,没有其他子元素)。

Please tell me how to fix this, especially for Firefox. 请告诉我如何解决此问题,尤其是对于Firefox。

Thank you. 谢谢。

HTML: HTML:

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

JavaScript: 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/ http://jsfiddle.net/bk7ade2r/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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