聊天室、表情面板、程式碼編輯器都需要「游標停在哪裡,字就插在哪裡」。瀏覽器沒有統一 API,因此要分攤:IE 走 document.selection,現代瀏覽器走 selectionStart/selectionEnd。
(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();
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);
呼叫方式:
$(selector).insertContent("插入的內容");
// 第二個參數用來選取插入文字兩側的邊界:
// 0 表示全選插入的文字,-1 表示兩側各少選一個字元。
function insertText(obj, str) {
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (typeof obj.selectionStart === 'number'
&& typeof obj.selectionEnd === 'number') {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str
+ tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
} else {
obj.value += str;
}
}
// 把游標移到內容末端
function moveEnd(obj) {
obj.focus();
var len = obj.value.length;
if (document.selection) {
var sel = obj.createTextRange();
sel.moveStart('character', len);
sel.collapse();
sel.select();
} else if (typeof obj.selectionStart == 'number'
&& typeof obj.selectionEnd == 'number') {
obj.selectionStart = obj.selectionEnd = len;
}
}
插入後一定要把焦點還給 textarea,並同步設定 selectionStart/End,否則游標會跳到最前面或最後面。若插入會改變捲動位置,記得先存 scrollTop 再還原,使用者體驗會好很多。