首頁  >  文章  >  web前端  >  jQuery實作在textarea指定位置插入字元或表情的方法_jquery

jQuery實作在textarea指定位置插入字元或表情的方法_jquery

WBOY
WBOY原創
2016-05-16 16:10:091487瀏覽

本文實例講述了jQuery實作在textarea指定位置插入字元或表情的方法。分享給大家供大家參考。具體實作方法如下:

1. 函數定義    

複製程式碼 程式碼如下:
(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;
                            地.                     this.focus();
                    $t.selectionStart = startPos myValue.length;
                    $t.selectionEnd = startPos myValue.length;
                    $t.scrollTop = scrollTop;
                }
                else {
                    this.value = myValue;
                    this.focus();
                }
        }
    }) 
})(jQuery);
2. 呼叫方法

複製程式碼 程式碼如下:
$("#textareaId").insertAtCaret("新表情"); 希望本文所述對大家的jQuery程式設計有所幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn