Jquery在光标位置插入内容

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

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

使用方法:

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

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