首页 > 开发 > Javascript > 正文

JQuery在光标位置插入内容的实现代码

2020-02-28 04:13:29
字体:
来源:转载
供稿:网友
代码如下:
(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);

使用方法:
代码如下: $(selector).insertAtCaret("value");
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表