jQuery从光标所在处插入内容

17-10-09 17:03 字数 615 阅读 2657 已编辑
(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);      

使用方法

$("#selector").insertAtCaret('test');  
0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论
站长 @ 十七度
文章
380
粉丝
23
喜欢
190
收藏
31
排名 : 1
访问 : 127.94万
私信