點擊某個元素要讓輸入框獲得焦點時,瀏覽器預設會把游標放在開頭,或者選起整段文字。若想讓游標停在內容尾端,得手動設定 selection 範圍。以下把它包成三個 jQuery 擴充方法。
// 設定游標位置
$.fn.setCursorPosition = function(position) {
if (this.length == 0) return this;
return $(this).setSelection(position, position);
};
// 設定選取範圍(start 與 end 相同即為單純的游標定位)
$.fn.setSelection = function(selectionStart, selectionEnd) {
if (this.length == 0) return this;
var input = this[0];
if (input.createTextRange) {
// 舊版 IE
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
} else if (input.setSelectionRange) {
// 標準瀏覽器
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
};
// 把游標移到內容最後
$.fn.focusEnd = function() {
this.setCursorPosition(this.val().length);
};
$('#myInput').focusEnd();
一行就能把焦點設好、游標停在尾端。
• setSelection(start, end) 是最底層的方法,直接操作瀏覽器的選取 API。start 與 end 相同就是純定位,不同就是選取一段文字。
• setCursorPosition(pos) 是 setSelection 的簡化版,專門用來定位。
• focusEnd() 是最實用的封裝,把 this.val().length 當成位置傳進去。
為什麼要判斷 createTextRange。IE 8 以下不支援 setSelectionRange,得走 document.createTextRange() 那套。現在已經是歷史包袱,但維護老系統時還是會遇到。
focus() 必須在 setSelectionRange 之前呼叫。順序顛倒的話,部分瀏覽器會因為元素尚未取得焦點而忽略選取設定。
原程式碼的 this.lengh 是拼字錯誤。正確应为 this.length。誤拼的結果是 undefined == 0 恆為 false,那個「空集合就提早回傳」的防呆判斷實際上永遠不會觸發。上面已修正。
把游標移到開頭:
$.fn.focusStart = function() {
this.setCursorPosition(0);
return this.focus();
};
全選內容(做「點一下就能整段複製」很順手):
$.fn.selectAll = function() {
this.setSelection(0, this.val().length);
return this;
};
另外別忘了在 focusEnd 裡補上 return this.focus() 之類的串接支援,實際操作上會方便一些。