萬盛學電腦網

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

JavaScript 讓輸入框聚焦時游標定位到文字末尾的跨瀏覽器方案

核心 API:setSelectionRange (現代標準)

function moveCursorToEnd(input) {
    if (!input) return;
    var len = input.value.length;
    // 聚焦並設定選區起點/終點皆為長度 (即末尾)
    input.focus();
    if (input.setSelectionRange) {
        input.setSelectionRange(len, len);
    }
    // 觸發 input 事件通知框架 (Vue/React 等)
    input.dispatchEvent(new Event('input', { bubbles: true }));
}

完整跨瀏覽器相容函式

function focusEnd(el) {
    el = (typeof el === 'string') ? document.getElementById(el) : el;
    if (!el || el.tagName !== 'INPUT' && el.tagName !== 'TEXTAREA') return;
    
    var val = el.value;
    el.focus();
    
    // 現代瀏覽器 (IE9+、所有現代瀏覽器)
    if (el.setSelectionRange) {
        // setSelectionRange 需在 focus 後調用,否則部分瀏覽器無效
        var len = val.length;
        el.setSelectionRange(len, len);
        return;
    }
    
    // IE 8- 專用:建立 TextRange
    if (el.createTextRange) {
        var range = el.createTextRange();
        range.collapse(false); // false = 移至結尾
        range.select();
    }
}

// 使用
$('#myInput').on('click', function() { focusEnd(this); });
// 或自動聚焦時
$(function() { focusEnd('#searchInput'); });

Vue / React 框架整合

Vue 3 Composition API

<script setup>
import { ref, onMounted, nextTick } from 'vue';

const inputRef = ref(null);
const focusEnd = (el) => {
    if (!el) return;
    const len = el.value.length;
    el.focus();
    nextTick(() => { el.setSelectionRange(len, len); });
};

onMounted(() => focusEnd(inputRef.value));

// 指令封裝 (v-focus-end)
export const vFocusEnd = {
    mounted(el) { focusEnd(el); },
    updated(el) { focusEnd(el); }
};
</script>

<template>
  <input ref="inputRef" v-focus-end />
</template>

React Hook

import { useRef, useEffect } from 'react';

function useFocusEnd(condition = true) {
    const ref = useRef(null);
    useEffect(() => {
        if (condition && ref.current) {
            const el = ref.current;
            const len = el.value.length;
            el.focus();
            // React 18+ 同步 focus 後需微任務才能 setSelectionRange
            setTimeout(() => el.setSelectionRange(len, len), 0);
        }
    }, [condition]);
    return ref;
}

// 使用
function SearchInput() {
    const inputRef = useFocusEnd(true);
    return ;
}

常見坑點與解決

現象原因解決
游標停在開頭先 setSelectionRange 再 focus()**先 focus,再 setSelectionRange**
React 中無效合成事件/批次更新導致時機錯誤setTimeout(() => el.setSelectionRange(len, len), 0) 或 useLayoutEffect
輸入法組合中誤動composition 中 value 未確定監聽 compositionend 後再處理
readonly/disabled 元素無法聚焦/選區先檢查 !el.readOnly && !el.disabled

進階:內容可編輯元素 (contenteditable)

function moveCaretToEnd(el) {
    el.focus();
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false); // 到末尾
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

效能提示

  • 極長文字 (超過 10萬字元) 設定選區可能導致主執行緒卡頓,考慮虛擬滾動或分頁編輯器。
  • 頻繁聚焦/選區操作建議去抖動。
copyright © 萬盛學電腦網 all rights reserved