js 在div光标位置加入内容

1.div指定位置插入内容

<html>
 <head></head>
 <body>
	<img id="pic" src="http://pagead2.googlesyndication.com/pagead/imgad?id=CICAgKCryu2pcxCAARiAATIIZaZ08qaakQY" />
  <div contenteditable="true" style="height:50px; border:2px solid red;" id="test"> 说了的飞机上了的解放了时间发了说了的房间里水电费就
  </div> 
  <script type="text/javascript">
	  var aa = document.getElementById('pic')
	  aa.onclick = function(){
	  	var a = this;
		  //alert(a)
		  insertHtmlAtCaret(a)
	  }
    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();
                // 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;
				el.appendChild(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>
 </body>
</html>
posted @ 2019-12-25 18:55  冲向蓝天  阅读(831)  评论(0)    收藏  举报