之前我爱模板网介绍了js在textarea输入框插入文字,今天利用可编辑的div(contentEditable="true"),仍旧配合js的createRange方法,找到光标位置,插入包含文字、图片等各种元素,废话不多说,放代码:
HTML代码:
<button type="button" onclick="insertHTML()">插入图片</button> <div contentEditable="true" style="border:2px solid red;" id="test"> </div>
JavaScript代码:
function insertHtmlAtCaret(html) { var sel, range; if (window.getSelection) { // IE9 and non-IE 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); // 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); } } function insertHTML(){ document.getElementById('richDiv').focus(); insertHtmlAtCaret('<img src="http://www.5imoban.net/view/demoimg/2.jpg">'); }