[英]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();
}
问题似乎是firefox无法将content()放在可编辑的div上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.