有些时候我们已经在textarea中输入了一些字符,然后想在鼠标指定的位置插入表情或者字符,这就需要用到jquery的一个小插件了。
代码如下:
(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);
我们写个小页面,测试一下该插件。
显示如下: