jQuery在textarea光标处插入文本

/** 
 * @param $ 
 * 自定义jQuery扩展方法, 在光标处插入内容 
 */  
(function ($) {  
    "use strict";  
    $.fn.extend({  
        insertAtCaret : function (myValue) {  
            var $t = $(this)[0];  
            if (document.selection) {  
                this.focus();  
                var 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);  

  调用方法:$("textarea").insertAtCaret("要出入的文本");


posted @ 2018-04-20 16:57  迷茫于红尘  阅读(421)  评论(0编辑  收藏  举报