# jQuery从光标所在处插入内容

**URL:** <https://www.shiqidu.com/t/topic/235>\
**Category:** 开发调优\
**Tags:** JavaScript\
**Created:** [2017 年10 月 9 日 09:03 UTC](https://www.shiqidu.com/t/topic/235 "2017-10-09T09:03:07Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2017 年10 月 9 日 09:03 UTC](https://www.shiqidu.com/t/topic/235/1 "2017-10-09T09:03:07Z")

</div>

```javascript
(function ($) {      
    $.fn.extend({      
        insertAtCaret : function (myValue) {      
            var $t = $(this)[0];      
            if (document.selection) {      
                this.focus();      
                sel = document.selection.createRange();      
                sel.text = myValue;      
                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;      
                $t.selectionEnd = startPos + myValue.length;      
                $t.scrollTop = scrollTop;      
            } else {      
                this.value += myValue;      
                this.focus();      
            }      
        }      
    })      
})(jQuery);      

```

使用方法

```javascript
$(&quot;#selector&quot;).insertAtCaret('test');  

```
