js 在鼠标光标处插入内容

最近手上的一个项目涉及到制作一个简易的富文本编辑器。
由于编辑器需要集成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
// elem 元素 需要带 # 或 .
// html 插入的内容
function insertHTML(elem,html) {
var dthis=$(elem)[0];//要插入内容的某个div,在标准浏览器中 无需这句话
//dthis.focus();
var sel, range;
if($(dthis).hasClass("flag")){
$(dthis).html(dthis.innerHTML+html);
return;
}
if (window.getSelection)
{
// IE9 and non-IE
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(); //在非标准浏览器中 要先让你需要插入html的div 获得焦点
ierange= document.selection.createRange();//获取光标位置
ierange.pasteHTML(html); //在光标位置插入html 如果只是插入text 则就是fus.text="..."
$(dthis).focus();

}
}

评论区