萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 在 textarea 游標位置插入文字或表情符號

在編輯器、留言板等場景,常需在文字游標處插入表情代碼、標籤或預設文字。本文提供一個通用的 jQuery 擴展 .insertAtCaret(),相容 IE(document.selection)與標準瀏覽器(selectionStart/End)。

擴展代碼

(function($) {
    $.fn.extend({
        insertAtCaret: function(myValue) {
            var $t = $(this)[0];
            if (document.selection) { // IE
                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);

使用方式

// 插入表情代碼
$("#textareaId").insertAtCaret("[emoji:smile]");

// 綁定表情面板點擊事件
$(".emoji-btn").click(function() {
    $("#textareaId").insertAtCaret($(this).data("code"));
});

關鍵點

  • 保存並恢復 scrollTop,防止長文本插入後頁面跳動。
  • 同時設定 selectionStart 與 selectionEnd 使游標停留在插入內容之後。
  • IE 使用 document.selection.createRange().text 取代選取內容。

現代補充:execCommand('insertText')

現代瀏覽器支援 document.execCommand('insertText', false, text)(需元素聚焦),可簡化插入邏輯,但該 API 已棄用,長期建議使用 InputEvent 或 ContentEditable 方案。

copyright © 萬盛學電腦網 all rights reserved