在開發中經常遇到「把游標自動移到輸入框最後」這類需求。本文整理了在 IE、Firefox、Opera 等主流瀏覽器上都能運作的游標位置取得(getCursortPosition)與設定(setCaretPosition)函式。
1. 取得游標位置的函式:
function getCursortPosition (ctrl) { var CaretPos = 0; // IE Support if (document.selection) { ctrl.focus (); var Sel = document.selection.createRange (); Sel.moveStart ('character', -ctrl.value.length); CaretPos = Sel.text.length; } // Firefox support else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart; return (CaretPos); } 2. 設定游標位置的函式:
function setCaretPosition(ctrl, pos){ if(ctrl.setSelectionRange) { ctrl.focus(); ctrl.setSelectionRange(pos,pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } 這兩個函式的關鍵都在於「跨瀏覽器判斷」:Firefox 等現代瀏覽器使用 selectionStart 與 setSelectionRange,而舊版 IE 則要透過 document.selection 與 createTextRange 搭配 moveStart、moveEnd 來定位。把游標設在輸入內容的尾端,只需將 pos 傳入字串長度即可,這在聊天輸入框、搜尋框等互動元件上非常實用。