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', '{' + 值+ '}');

posted @ 2018-03-14 15:39  D调灬仔  阅读(323)  评论(0编辑  收藏  举报

作者D调灬仔

出处:https://www.cnblogs.com/chj929555796/

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!