zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

jQuery代码 实现 内容 插入 位置 光标
2023-06-13 09:14:23 时间
复制代码代码如下:

(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"){
varstartPos=$t.selectionStart;
varendPos=$t.selectionEnd;
varscrollTop=$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");