萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 將輸入框游標定位至文字末尾:跨瀏覽器相容實作

讓輸入框聚焦時游標自動跳至文字末尾:TextRange 與 setSelectionRange 雙模式相容方案

表單體驗優化中常見需求:輸入框獲得焦點時,游標自動定位到現有文字末尾,方便用戶直接追加輸入。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

jQuery 版本封裝(含鏈式支援)

$.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/Vue 等現代框架中的處理

{/* 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="初始值" />

常見坑點

  1. 元素未渲染/不可見時調用:確保元素已掛載 DOM 且 display !== 'none'。
  2. type="hidden"、disabled、readonly 元素無法聚焦/選取。
  3. IE 需先 focus 再操作 range:el.focus(); range.select(); 順序不可顛倒。
  4. 中文輸入法組合中:compositionstart/end 期間操作選區可能導致組合文字丟失,建議在 compositionend 後處理。

掌握這個小技巧,能顯著提升表單密集型應用(後台管理、聊天輸入、代碼編輯器)的使用者體驗。

copyright © 萬盛學電腦網 all rights reserved