我需要在contenteditable div中使用#id设置DOM元素之后的插入位置。通过这种方式,我将能够继续输入文字。
一般问题是
示例html结构:
<div id="container" contenteditable="true">
dasidjsaid<div id="el1">sdsad</div>fdfhsdhdsf<div id="el2">sdsad</div>afasf
<div id="el3">test</div><div id="el4">jsj</div> <div id="el5">32</div>sadsa
</div>
答案 0 :(得分:0)
尝试一下:
function setToStart(element) {
if(!element) {
return;
}
element.focus();
var range = document.createRange();
range.setStart(element, 0);
range.setEnd(element, 0);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
try {
sel.addRange(range);
} catch (e) { }
}
function setToEnd(element) {
element.focus();
var nodeStack = [element];
var node = null;
var lastNode = element;
var charIndex = 0;
while ((node = nodeStack.pop())) {
if (node.nodeType === 3) {
lastNode = node;
charIndex = node.length;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var range = document.createRange();
range.setStart(lastNode, charIndex);
range.setEnd(lastNode, charIndex);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
try {
sel.addRange(range);
} catch (e) { }
}
document.getElementById('setStart').addEventListener('click', function() {
setToStart(document.getElementById('first'));
});
document.getElementById('setEnd').addEventListener('click', function() {
setToEnd(document.getElementById('first'));
});
&#13;
<div contenteditable="true"><h1>Title</h1><p id="first">Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Cras justo odio, dapibus ac facilisis in, egestas eget quam.</p><p id="second">Nulla vitae elit libero, a pharetra augue. Aenean lacinia bibendum nulla sed consectetur.</p></div>
<button id="setStart">Set to START of first paragraph</button>
<button id="setEnd">Set to END of first paragraph</button>
&#13;