jquery往textarea鼠标光标选中的地方插入值
一、textarea
1、扩展jquery函数
(function ($) {
"use strict";
$.fn.extend({
insertAtCaret: function (myValue) {
var $t = $(this)[0];
if (document.selection) {
this.focus();
var 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);
2、调用函数
$("#ID").insertAtCaret‘值’);
二、百度编辑器
1、初始化编辑器内鼠标最后停留的地方
UM.getEditor('ID').focus();
2、调用
UM.getEditor('ID').execCommand('inserthtml', '{' + 值+ '}');