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

相关文章:

  • 2021-07-19
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
  • 2022-12-23
猜你喜欢
  • 2021-08-26
  • 2022-12-23
  • 2021-10-07
  • 2022-01-08
  • 2021-10-11
相关资源
相似解决方案