jquery.caretInsert.js
1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(function ($) {
$.fn.extend({
/**
* 在文本框的光标位置插入指定字符串,并将光标前移指定位数
* @param myValue 插入字符串
* @param len 前移位数
*/
insertAtCaret: function (myValue, len) {
if (!len || isNaN(len)) {
len = 0;
}
var $t = $(this)[0];
//IE
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.moveStart("character", 0 - len);
sel.collapse(true);
sel.select();
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 - len;
$t.selectionEnd = startPos + myValue.length - len;
$t.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
}
})
})(jQuery);