Skip to content

Instantly share code, notes, and snippets.

@greycode
Last active December 17, 2015 16:08
Show Gist options
  • Save greycode/5636096 to your computer and use it in GitHub Desktop.
Save greycode/5636096 to your computer and use it in GitHub Desktop.
如何在可编辑的DIV标签中插入一段 HTML 代码。 how to insert HTML to a contenteditable DIV (IE6+)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> TEST </title>
<style type="text/css">
.container { border: 1px solid blue;height: 200px;padding: 5px;width: 100%; }
.container p { margin:0;padding:0; }
.holder { border:1px dashed black; margin:0 2px 0 2px; padding: 0 3px 0 3px;}
</style>
</head>
<body>
<div id="editorDiv" class="container" contenteditable="true">
hello
<span class="holder" contenteditable="true" oncontrolselect="javascript:return false">world</span>
<!-- <span class="holder" contenteditable="true" unselectable="on">world</span> -->
</div>
<input type="button" value="TEST" onclick="mainTest()"/>
</body>
<script type="text/javascript">
<!--
//document.designMode = 'on';
function mainTest() {
pasteHtmlAtCaret('<span class="holder" contenteditable="true" unselectable="on">world</span>')
alert(document.getElementById('editorDiv').innerText)
}
function pasteHtmlAtCaret(html) {
var sel, range;
document.getElementById('editorDiv').focus();
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
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);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
//-->
</script>
</html>
@greycode
Copy link
Author

参考 一步步教你实现富本文编辑器(第一部分)
http://blog.csdn.net/cheng5128/article/details/4613809

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment