JQuery在光标位置插入内容

时间:2021-08-20 10:54:09
 1 (function($) {
 2     $.fn.extend({
 3         insertAtCaret: function(myValue) {
 4             var $t = $(this)[0];
 5               //IE
 6             if (document.selection) {
 7                 this.focus();
 8                 sel = document.selection.createRange();
 9                 sel.text = myValue;
10                 this.focus();
11             } else
12             //!IE
13             if ($t.selectionStart || $t.selectionStart == "0") {
14                 var startPos = $t.selectionStart;
15                 var endPos = $t.selectionEnd;
16                 var scrollTop = $t.scrollTop;
17                 $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
18                 this.focus();
19                 $t.selectionStart = startPos + myValue.length;
20                 $t.selectionEnd = startPos + myValue.length;
21                 $t.scrollTop = scrollTop;
22             } else {
23                 this.value += myValue;
24                 this.focus();
25             }
26         }
27     })
28 })(jQuery);

 

IE下可以通过document.selection.createRange();来实现,而Firefox(火狐)浏览器则需要首先获取光标位置,然后对value进行字符串截取处理。
$(selector).insertAtCaret("value");