JQ在鼠标光标的文本内插入内容
展开阅读全文

JQuery在光标位置插入内容

<tr>
<td class="label">内容:</td>
    <td><textarea name="content" class="myInput content" cols="70" rows="6" style="font-size:12px;"></textarea>
</td>
</tr>
<script>
(function($) {
    $.fn.extend({
        insertAtCaret: function(myValue) {
            var $t = $(this)[0];
              //IE
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else
            //!IE
            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);
$('.content').insertAtCaret("{变量}");
</script>

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