在做聊天室、表情插入或編輯器時,我們常需要在使用者目前的光標位置插入一段文字,而不是把內容附加到最後。這牽涉到跨瀏覽器的差異:IE 使用 document.selection,而 Firefox、Chrome、Safari、Opera 則提供 selectionStart 與 selectionEnd 屬性。下面的程式碼把兩種情況都兼顧了。
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;
}
}
<input type="button" onclick="insertText(document.getElementById('text'),' 新文字—YoyiorLee ')" value="插入文字">
<input type="button" onclick="moveEnd(document.getElementById('text'))" value="移到末尾">
insertText 會先取得目前光標的起點與終點,把選取範圍用新字串替換掉,再把光標移到插入內容之後;若環境不支援這些屬性,就退回最簡單的「附加到結尾」。而 moveEnd 則負責讓光標跳到文字最末端,方便插入後繼續輸入。透過這兩個函式,就能打造順手且跨瀏覽器一致的光標操作體驗。