div与textarea插入qq表情代码并停留在光标处
1、div中插入qq表情 注:使用此种方式会将表情插入到div外面 View: <div class="editArea"> <div style="border: 1px solid black; height: 100px;" contenteditable="true" id="msgTxt"></div> <div contenteditable="true" style="overflow-y: auto; overflow-x: hidden;"></div> </div> JS: $('#msgTxt').insertAtCaret('<img src="/Content/images/faces/' + key + '" title="' + val + '"/>'); jQuery.fn.extend({ insertAtCaret: function (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; 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); } } }); 2、div中插入qq表情 <div class="editArea"> <div style="border: 1px solid black; height: 100px;" contenteditable="true" id="msgTxt"></div> <div contenteditable="true" style="overflow-y: auto; overflow-x: hidden;"></div> </div> JS: inimage('<img src="/Content/images/faces/' + key + '" title="' + val + '"/>'); function inimage(text) { var obj = $("#msgTxt")[0]; var range, node; if (!obj.hasfocus) { obj.focus(); } if (window.getSelection && window.getSelection().getRangeAt) { range = window.getSelection().getRangeAt(0); range.collapse(false); node = range.createContextualFragment(text); var c = node.lastChild; range.insertNode(node); if (c) { range.setEndAfter(c); range.setStartAfter(c) } var j = window.getSelection(); j.removeAllRanges(); j.addRange(range); } else if (document.selection && document.selection.createRange) { document.selection.createRange().pasteHTML(text); } }