jQuery 输入框 在光标位置插入内容, 并选中

//
02 //使用方法
03 //$(文本域选择器).insertContent("插入的内容");
04 //$(文本域选择器).insertContent("插入的内容",数值); //根据数值选中插入文本内容两边的边界, 数值: 0是表示插入文字全部选择,-1表示插入文字两边各少选中一个字符。
05 //
06 //在光标位置插入内容, 并选中
07 (function($) {
08     $.fn.extend({
09         insertContent: function(myValue, t) {
10             var $t = $(this)[0];
11             if (document.selection) { //ie
12                 this.focus();
13                 var sel = document.selection.createRange();
14                 sel.text = myValue;
15                 this.focus();
16                 sel.moveStart('character', -l);
17                 var wee = sel.text.length;
18                 if (arguments.length == 2) {
19                     var l = $t.value.length;
20                     sel.moveEnd("character", wee + t);
21                     t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length);
22    
23                     sel.select();
24                 }
25             } else if ($t.selectionStart || $t.selectionStart == '0') {
26                 var startPos = $t.selectionStart;
27                 var endPos = $t.selectionEnd;
28                 var scrollTop = $t.scrollTop;
29                 $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
30                 this.focus();
31                 $t.selectionStart = startPos + myValue.length;
32                 $t.selectionEnd = startPos + myValue.length;
33                 $t.scrollTop = scrollTop;
34                 if (arguments.length == 2) {
35                     $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
36                     this.focus();
37                 }
38             }
39             else {
40                 this.value += myValue;
41                 this.focus();
42             }
43         }
44     })
45 })(jQuery);
posted @ 2011-11-09 09:41  peterlee  阅读(602)  评论(0)    收藏  举报