最近刚好碰到这个问题,虽然离提出问题已经过了半年了,本着前人栽树后人乘凉的精神,还是回答一下。
效果:
<div id="editor" contenteditable="true"></div>
$("#Modal .emoji-list li").click(function(event) { var emoji = $(this).find("img").attr('src'); $("#editor").focus(); var source = '<img src="'+emoji+'">'; _insertimg(source); }); function _insertimg(str){ var selection= window.getSelection ? window.getSelection() : document.selection; var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0); if (!window.getSelection){ document.getElementById('editor').focus(); var selection= window.getSelection ? window.getSelection() : document.selection; var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0); range.pasteHTML(str); range.collapse(false); range.select(); } else{ document.getElementById('editor').focus(); range.collapse(false); var hasR = range.createContextualFragment(str); var hasR_lastChild = hasR.lastChild; while (hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") { var e = hasR_lastChild; hasR_lastChild = hasR_lastChild.previousSibling; hasR.removeChild(e) } range.insertNode(hasR); if (hasR_lastChild) { range.setEndAfter(hasR_lastChild); range.setStartAfter(hasR_lastChild) } selection.removeAllRanges(); selection.addRange(range) } }
参照的原文在这里,里面用不同的方法分别进行了实现:
js实现在光标的位置 添加内容
from:https://www.zhihu.com/question/39811839/answer/83947340