用 DOM 操作 textarea 裡的文字向來麻煩,最大的痛點是光標位置——IE 走 document.selection 與 TextRange,標準瀏覽器走 selectionStart/setSelectionRange,兩套完全不同的 API。以下把常用操作封裝成一個 TT 物件,測試過 IE6、IE8、Firefox、Chrome、Opera 與 Safari,相容性沒問題。
有一個已知的小毛病:Firefox 下重新賦值 value 會使 scrollTop 歸零,這裡用暫存再還原的方式繞過,雖然有效但不算完美。若有更好的解法,歡迎指點。
var TT = {
/*
* 獲取光標位置
* @param t element
* @return number
*/
getCursorPosition: function(t){
if (document.selection) {
t.focus();
var ds = document.selection;
var range = ds.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText(t);
stored_range.setEndPoint("EndToEnd", range);
t.selectionStart = stored_range.text.length - range.text.length;
t.selectionEnd = t.selectionStart + range.text.length;
return t.selectionStart;
} else return t.selectionStart;
},
/*
* 設置光標位置
* @param t element
* @param p number
*/
setCursorPosition: function(t, p){
this.sel(t, p, p);
},
/*
* 插入到光標後面
* @param t element
* @param txt String
*/
add: function (t, txt){
var val = t.value;
if(document.selection){
t.focus();
document.selection.createRange().text = txt;
} else {
var cp = t.selectionStart;
var ubbLength = t.value.length;
var s = t.scrollTop;
t.value = t.value.slice(0, t.selectionStart) + txt
+ t.value.slice(t.selectionStart, ubbLength);
this.setCursorPosition(t, cp + txt.length);
// 修正 Firefox 下 scrollTop 被歸零的問題
firefox = navigator.userAgent.toLowerCase().match(/firefox\/([\d\.]+)/)
&& setTimeout(function(){
if(t.scrollTop != s) t.scrollTop = s;
}, 0);
}
},
/*
* 刪除光標前面或後面的 n 個字符
* @param t element
* @param n number n > 0 刪後面 n 個;n < 0 刪前面
* 重新設置 value 時 scrollTop 會被清 0
*/
del: function(t, n){
var p = this.getCursorPosition(t);
var s = t.scrollTop;
var val = t.value;
t.value = n > 0 ? val.slice(0, p - n) + val.slice(p)
: val.slice(0, p) + val.slice(p - n);
this.setCursorPosition(t, p - (n < 0 ? 0 : n));
firefox = navigator.userAgent.toLowerCase().match(/firefox\/([\d\.]+)/)
&& setTimeout(function(){
if(t.scrollTop != s) t.scrollTop = s;
}, 10);
},
/*
* 選中 s 到 z 位置的文字
* @param t element
* @param s number
* @param z number
*/
sel: function(t, s, z){
if(document.selection){
var range = t.createTextRange();
range.moveEnd('character', -t.value.length);
range.moveEnd('character', z);
range.moveStart('character', s);
range.select();
}else{
t.setSelectionRange(s, z);
t.focus();
}
},
/*
* 選中一個指定的字符串
* @param t element
* @param s String
*/
selString: function(t, s){
var index = t.value.indexOf(s);
index != -1 ? this.sel(t, index, index + s.length) : false;
}
}
幾個使用重點:add 是插入表情符號、UBB 標籤這類功能的核心;del 的參數正負決定往光標前還是後刪;selString 則適合做「搜尋並高亮」。
標準瀏覽器其實提供了更省事的做法,可以大幅簡化上面的程式碼:
// 插入文字到光標處
function insertAtCursor(el, text) {
const start = el.selectionStart;
const end = el.selectionEnd;
el.setRangeText(text, start, end, 'end'); // 會保留原生的 undo 堆疊
el.focus();
}
// 取得選中的文字
const selected = el.value.slice(el.selectionStart, el.selectionEnd);
setRangeText 的好處是瀏覽器會正確維護復原(undo)功能,而直接改 value 不會——這是「手動改 value」路線最大的缺點,使用者按 Ctrl+Z 會發現剛插入的內容無法復原。至于 Firefox 的 scrollTop 問題,只要別去動 value(改用 setRangeText),自然也就不會發生。