最近手上的一个项目涉及到制作一个简易的富文本编辑器。
由于编辑器需要集成emoji表情功能。所以需要获取焦点光标的位置然后插入emoji表情。
在网上尝试过多种方法,比如这种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| (function ($) { $.fn.extend({ insertAtCaret: function (myValue) { var $t = $(this)[0]; if (document.selection) { this.focus(); sel = document.selection.createRange(); sel.text = myValue; this.focus(); } else if ($t.selectionStart || $t.selectionStart == '0') { var startPos = $t.selectionStart; var endPos = $t.selectionEnd; var scrollTop = $t.scrollTop; $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); this.focus(); $t.selectionStart = startPos + myValue.length; $t.selectionEnd = startPos + myValue.length; $t.scrollTop = scrollTop; } else { this.value += myValue; this.focus(); } } }) })(jQuery);
|
最后找到一个可以用的js函数(依赖js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
function insertHTML(elem,html) { var dthis=$(elem)[0]; var sel, range; if($(dthis).hasClass("flag")){ $(dthis).html(dthis.innerHTML+html); return; } if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); 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); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type !='Control') { $(dthis).focus(); ierange= document.selection.createRange(); ierange.pasteHTML(html); $(dthis).focus();
} }
|