zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    java
    java
    java
    java
    java
    java
    java
    java
    sed命令的用法
    linux系统产生随机数的6种方法
  • 原文地址:https://www.cnblogs.com/BluceLee/p/12098424.html
Copyright © 2011-2022 走看看