<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<button type="button" onclick="insertHtmlAtCaret('<span>插入成功</span>');">插入字符
</button>
<div contentEditable="true" id="test1" style="height:50px; border:2px solid red;" >111111111111111111111111</div>
<div contentEditable="true" style="height:50px; border:2px solid red;" >222222222222222222222222</div>
<script>
function insertHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
}
</script>
现在有两个div,点击哪个div然后再点插入内容,就会把内容插入光标所在的地方,但是能否让他插入指定id = test1 的div光标里,如果没有点击光标就插入到 test1 的最尾部,求大神帮忙修改下
div上哪來的光標..
contentEditable="true" 加入这个标签后,就可以输入文字了
@-JackoChan:
FYI
http://www.examplet.org/jquery/caret.php
@RosonJ: 这个是input框的,不过还是非常感谢你的帮忙