部落格後台插入圖片語法、聊天室插入表情符號、編輯器插入變數模板——這些功能的共同點都是「在游標當前位置插入一段文字」,而不是附加在結尾。本文示範如何把這個能力封裝成 jQuery 外掛。
<html>
<head>
<script src="jquery-1.8.1.min.js"></script>
<script>
$(function () {
/* 在 textarea 游標處插入文字 */
(function ($) {
$.fn.extend({
insertContent: function (myValue, t) {
var $t = $(this)[0];
if (document.selection) {
// 舊 IE 分支
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
sel.moveStart('character', -l);
var wee = sel.text.length;
if (arguments.length == 2) {
var l = $t.value.length;
sel.moveEnd("character", wee + t);
t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length)
: sel.moveStart("character", wee - t - myValue.length);
sel.select();
}
} 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;
if (arguments.length == 2) {
$t.setSelectionRange(startPos - t, $t.selectionEnd + t);
this.focus();
}
} else {
this.value += myValue; // 無法取得游標位置時,附加到結尾
this.focus();
}
}
});
})(jQuery);
$("#ch_button").click(function () {
$("#test_in").insertContent("<upload/day_140627/201406271546349972.jpg>");
});
});
</script>
</head>
<body>
<button id="ch_button" value="插入">插入</button>
<textarea name="content" id="test_in" rows="30" cols="100"></textarea>
</body>
</html>
核心只有三步:先用 selectionStart / selectionEnd 記住插入點,再用 substring 把 value 拆成「前段 + 新內容 + 後段」重組,最後把游標移到插入內容之後。
有幾個細節值得注意:插入前先記下 scrollTop,插入後再設回去,避免捲動位置跳掉;第二個參數 t 是額外的「往回選取」偏移量,插入完畢後可以用它反選一段文字,方便使用者直接覆寫。
document.selection 是 IE 專屬 API,現已無需照顧。現代寫法可以用 setRangeText() 一行完成插入並自動處理游標位置:
var el = document.getElementById('test_in');
el.setRangeText('<image>', el.selectionStart, el.selectionEnd, 'end');
el.focus();
若還要支援「插入後選取剛插入的文字」,把第四個參數改成 'select' 即可,程式碼大幅精簡,行為也更可靠。