在編輯器、留言板等場景,常需在文字游標處插入表情代碼、標籤或預設文字。本文提供一個通用的 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 使游標停留在插入內容之後。document.selection.createRange().text 取代選取內容。execCommand('insertText')現代瀏覽器支援 document.execCommand('insertText', false, text)(需元素聚焦),可簡化插入邏輯,但該 API 已棄用,長期建議使用 InputEvent 或 ContentEditable 方案。