表單體驗優化中常見需求:輸入框獲得焦點時,游標自動定位到現有文字末尾,方便用戶直接追加輸入。IE 老版本使用 TextRange,現代瀏覽器使用 setSelectionRange,本文提供完整相容封裝。
/**
* 將輸入框/文字區域游標移至內容末尾
* @param {HTMLInputElement|HTMLTextAreaElement} el - 目標元素
*/
function moveCursorToEnd(el) {
if (!el) return;
// 現代瀏覽器 (IE11+, Edge, Chrome, Firefox, Safari)
if (typeof el.setSelectionRange === 'function') {
var len = el.value.length;
el.setSelectionRange(len, len);
return;
}
// IE 9- 使用 TextRange
if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(false); // false = 移至結尾
range.select();
}
}
// 使用範例
<input type="text" id="myInput" value="預設文字" onfocus="moveCursorToEnd(this)" />
<textarea id="myTextarea" onfocus="moveCursorToEnd(this)">預設內容</textarea>
| API | 支援環境 | 關鍵參數/方法 |
|---|---|---|
setSelectionRange(start, end) | HTML5 標準,所有現代瀏覽器 | start=end=value.length 即為末尾 |
createTextRange() | IE 4-10 (IE11 已支援 setSelectionRange) | range.collapse(false) 移至結尾,range.select() 套用 |
selectionStart/End | 現代瀏覽器屬性 | 可直接賦值 el.selectionStart = el.selectionEnd = len |
$.fn.cursorToEnd = function () {
return this.each(function () {
var el = this;
var len = el.value.length;
if (el.setSelectionRange) {
el.setSelectionRange(len, len);
} else if (el.createTextRange) {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
});
};
// 使用
$('#myInput').on('focus', function () {
$(this).cursorToEnd();
});
/**
* 在游標位置插入文字,並將游標移至插入內容之後
* @param {HTMLInputElement|HTMLTextAreaElement} el
* @param {string} text - 要插入的文字
*/
function insertAtCursor(el, text) {
if (!el) return;
// 現代瀏覽器
if (typeof el.setSelectionRange === 'function') {
var start = el.selectionStart;
var end = el.selectionEnd;
el.value = el.value.substring(0, start) + text + el.value.substring(end);
el.setSelectionRange(start + text.length, start + text.length);
el.focus();
return;
}
// IE 9- (需先 focus 才能操作 selection)
if (document.selection && document.selection.createRange) {
el.focus();
var range = document.selection.createRange();
range.text = text;
range.collapse(false);
range.select();
}
}
// 使用:表情符號插入、模板快捷輸入等
$('#emoji-btn').on('click', function () {
insertAtCursor(document.getElementById('chat-input'), '😀');
});
{/* React Hook 版本 */}
function useCursorToEnd() {
const ref = useRef(null);
const moveToEnd = useCallback(() => {
if (ref.current) {
const len = ref.current.value.length;
if (ref.current.setSelectionRange) {
ref.current.setSelectionRange(len, len);
}
}
}, []);
return [ref, moveToEnd];
}
// 組件內
const [inputRef, moveToEnd] = useCursorToEnd();
<input ref={inputRef} onFocus={moveToEnd} defaultValue="初始值" />
display !== 'none'。type="hidden"、disabled、readonly 元素無法聚焦/選取。el.focus(); range.select(); 順序不可顛倒。compositionstart/end 期間操作選區可能導致組合文字丟失,建議在 compositionend 後處理。掌握這個小技巧,能顯著提升表單密集型應用(後台管理、聊天輸入、代碼編輯器)的使用者體驗。