js 在div光标位置加入内容

完整代码,可以自己测试

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>

textarea 光标位置输入内容

<!DOCTYPE html>
<html>
 <head> 
  <meta charset="utf-8" /> 
  <title>无标题文档</title> 
 </head> 
 <body> 
  <script type="text/javascript">   
function setCaret(textObj) {
    if (textObj.createTextRange) {
        textObj.caretPos = document.selection.createRange().duplicate();
    }
}
function insertAtCaret(textObj, textFeildValue) {
    if (document.all) {
        if (textObj.createTextRange && textObj.caretPos) {
            var caretPos = textObj.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == '   ' ? textFeildValue + '   ' : textFeildValue;
        } else {
            textObj.value = textFeildValue;
        }
    } else {
        if (textObj.setSelectionRange) {
            var rangeStart = textObj.selectionStart;
            var rangeEnd = textObj.selectionEnd;
            var tempStr1 = textObj.value.substring(0, rangeStart);
            var tempStr2 = textObj.value.substring(rangeEnd);
            textObj.value = tempStr1 + textFeildValue + tempStr2;
        } else {
            alert("This   version   of   Mozilla   based   browser   does   not   support   setSelectionRange");
        }
    }
}   
 </script> 
  <form id="form1" action="" onsubmit="" method="post" enctype="text/plain"> 
   <p> <textarea name="tarea" rows="" cols="" style="width:300px;height:120px;" onselect="setCaret(this);" onclick="setCaret(this);" onkeyup="setCaret(this);">例子例子例子例子例子</textarea> <br /><br /> <input type="text" name="textfield" style="width:220px;" value="插入FireFox" /> <br /> <input type="button" value="插入" onclick="insertAtCaret(this.form.tarea,this.form.textfield.value);" /> </p> 
  </form> 
  <div id="box" contenteditable="true" style="border:1px solid #ccc; width:300px; height:200px;">
   sljfldjfldf
  </div>  
 </body>
</html>

稍做修改

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>wechat</title>
    <style>
        div {
            width: 100%;
            height: 300px;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <div contenteditable="true" id="editor">这里写<img src="./img/1.jpg">东西进去</div>
    <img id="img" src="./img/1.jpg" alt="">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script>
        let editor = document.querySelector('#editor')
        let img = document.querySelector('#img')
        var range;  // 定义最后光标对象
        editor.onclick = function () {
            // 获取选定对象
            var sel = window.getSelection();
            if(sel.rangeCount && sel.getRangeAt){
                range = sel.getRangeAt(0);
                range.deleteContents()
            }
        }
        editor.onkeyup = function(){
            var sel = window.getSelection();
            if(sel.rangeCount && sel.getRangeAt){
                // 设置最后光标对象
                range = sel.getRangeAt(0);
                range.deleteContents()
            }
        }
        img.onclick = function(){
            // console.log(range)
            var sel = window.getSelection();
            var cloneEl = this.cloneNode(true)
            // var frag = document.createDocumentFragment()
            // frag.appendChild(cloneEl)

            console.dir(cloneEl)
            range.insertNode(cloneEl);

            range = range.cloneRange();
            range .setStartAfter(cloneEl)
            range.collapse(true);
            // 存在最后光标对象,选定对象清除所有光标并添加最后光标还原之前的状态
            sel.removeAllRanges();
            sel.addRange(range)
        }
    </script>
</body>

</html>

感谢网友贡献

枫叶布 https://www.cnblogs.com/sghy/p/7462870.html

smartsmile2012 https://blog.csdn.net/smartsmile2012/article/details/53642082

相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页