jquery.caretInsert.js 1.35 KB
(function ($) {
    $.fn.extend({
        /**
         * 在文本框的光标位置插入指定字符串,并将光标前移指定位数
         * @param myValue 插入字符串
         * @param len 前移位数
         */
        insertAtCaret: function (myValue, len) {
            if (!len || isNaN(len)) {
                len = 0;
            }
            var $t = $(this)[0];
            //IE
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                sel.moveStart("character", 0 - len);
                sel.collapse(true);
                sel.select();
                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 - len;
                $t.selectionEnd = startPos + myValue.length - len;
                $t.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        }
    })
})(jQuery);