Jquery在光标位置插入内容

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

(function($){
02 $.fn.extend({
03 insertAtCaret: function(myValue){
04 var $t=$(this)[0];
05 if (document.selection) {
06 this.focus();
07 sel = document.selection.createRange();
08 sel.text = myValue;
09 this.focus();
10 }
11 else
12 if ($t.selectionStart || $t.selectionStart == '0') {
13 var startPos = $t.selectionStart;
14 var endPos = $t.selectionEnd;
15 var scrollTop = $t.scrollTop;
16 $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
17 this.focus();
18 $t.selectionStart = startPos + myValue.length;
19 $t.selectionEnd = startPos + myValue.length;
20 $t.scrollTop = scrollTop;
21 }
22 else {
23 this.value += myValue;
24 this.focus();
25 }
26 }
27 })
28 })(jQuery);

使用方法:

1 $(selector).insertAtCaret("value");

 

转自http://www.popo4j.com/article/Jquery-insert-content-at-the-cursor-position.html

posted on 2011-01-14 20:06  senly  阅读(417)  评论(0编辑  收藏  举报

导航