萬盛學電腦網

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

jQuery 在 Textarea 光標位置插入文本:跨瀏覽器兼容實現與現代原生 API 方案

核心難點

不同瀏覽器獲取/設置光標位置的 API 歷史上差異巨大:

  • IE ≤ 8: `document.selection.createRange()`
  • 現代瀏覽器: `selectionStart`、`selectionEnd`、`setRangeText()`
  • 舊版 Firefox/Opera: 不同屬性名

原文 jQuery 插件代碼分析

$.fn.extend({
    insertContent: function(myValue, t) {
        const $t = this[0];
        
        if (document.selection) { // IE 老版本
            this.focus();
            const sel = document.selection.createRange();
            sel.text = myValue;
            this.focus();
            // ... 復雜的選區恢復邏輯
        } 
        else if ($t.selectionStart || $t.selectionStart === 0) { // 現代瀏覽器
            const startPos = $t.selectionStart;
            const endPos = $t.selectionEnd;
            const scrollTop = $t.scrollTop;
            
            $t.value = $t.value.substring(0, startPos) 
                     + myValue 
                     + $t.value.substring(endPos);
            
            this.focus();
            $t.selectionStart = startPos + myValue.length;
            $t.selectionEnd = startPos + myValue.length;
            $t.scrollTop = scrollTop;
            
            // 可選參數 t:調整選區
            if (arguments.length === 2) {
                $t.setSelectionRange(startPos - t, $t.selectionEnd + t);
            }
        } 
        else {
            // 兜底:直接追加
            this.value += myValue;
            this.focus();
        }
    }
});

現代標準實現 (原生 JS,無 jQuery 依賴)

function insertAtCursor(textarea, text, options = {}) {
    const {selectAfter = false, replaceSelection = true} = options;
    
    // 聚焦確保選區有效
    textarea.focus();
    
    // 現代 API:setRangeText 一行搞定
    // 參數:替換文本、開始、結束、選區模式
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    
    if (replaceSelection || start !== end) {
        textarea.setRangeText(text, start, end, selectAfter ? 'select' : 'end');
    } else {
        // 無選區且不替換:插入位置
        textarea.setRangeText(text, start, end, 'end');
    }
    
    // 保持滾動位置 (setRangeText 會自動處理大多數情況)
    // 如需精確控制可手動恢復 scrollTop
}

// 使用
const ta = document.getElementById('editor');
insertAtCursor(ta, '插入的文本');
insertAtCursor(ta, '**粗體**', {selectAfter: true}); // 插入並選中

完整功能封裝:TextareaEditor 類

class TextareaEditor {
    constructor(textarea) {
        this.ta = textarea;
    }
    
    // 核心:插入文本
    insert(text, {select = false, replace = true} = {}) {
        this.ta.focus();
        const s = this.ta.selectionStart;
        const e = this.ta.selectionEnd;
        this.ta.setRangeText(text, s, e, select ? 'select' : replace ? 'end' : 'preserve');
        return this;
    }
    
    // 包裹選區 (如 Markdown 語法)
    wrap(prefix, suffix = prefix) {
        const s = this.ta.selectionStart;
        const e = this.ta.selectionEnd;
        const selected = this.ta.value.slice(s, e);
        this.insert(prefix + selected + suffix, {select: true});
        return this;
    }
    
    // 獲取/設置選區
    getSelection() {
        return {
            start: this.ta.selectionStart,
            end: this.ta.selectionEnd,
            text: this.ta.value.slice(this.ta.selectionStart, this.ta.selectionEnd)
        };
    }
    
    setSelection(start, end) {
        this.ta.setSelectionRange(start, end);
        this.ta.focus();
        return this;
    }
    
    // 行操作
    getCurrentLine() {
        const {selectionStart: s, value} = this.ta;
        const lineStart = value.lastIndexOf('\n', s - 1) + 1;
        const lineEnd = value.indexOf('\n', s);
        return {
            start: lineStart,
            end: lineEnd === -1 ? value.length : lineEnd,
            text: value.slice(lineStart, lineEnd === -1 ? value.length : lineEnd)
        };
    }
    
    // 在行首/行尾插入
    insertAtLineStart(text) {
        const {start} = this.getCurrentLine();
        this.ta.setRangeText(text, start, start, 'end');
    }
    
    insertAtLineEnd(text) {
        const {end} = this.getCurrentLine();
        this.ta.setRangeText(text, end, end, 'end');
    }
}

// 使用
const editor = new TextareaEditor(document.getElementById('md-editor'));
$('#boldBtn').click(() => editor.wrap('**'));
$('#italicBtn').click(() => editor.wrap('*'));
$('#codeBtn').click(() => editor.wrap('`'));
$('#linkBtn').click(() => editor.wrap('[', '](url)'));

Vue 3 / React 集成

Vue 3 組合式函數

export function useTextareaEditor(textareaRef) {
    const editor = computed(() => textareaRef.value ? new TextareaEditor(textareaRef.value) : null);
    
    const insert = (text, opts) => editor.value?.insert(text, opts);
    const wrap = (pre, suf) => editor.value?.wrap(pre, suf);
    const getSelection = () => editor.value?.getSelection();
    
    return {insert, wrap, getSelection};
}

// 組件中
const textareaRef = ref(null);
const {insert, wrap} = useTextareaEditor(textareaRef);

React Hook

function useTextareaEditor() {
    const ref = useRef(null);
    const editor = useMemo(() => ref.current ? new TextareaEditor(ref.current) : null, []);
    
    const insert = useCallback((text, opts) => editor?.insert(text, opts), [editor]);
    const wrap = useCallback((pre, suf) => editor?.wrap(pre, suf), [editor]);
    
    return {ref, insert, wrap};
}

// 組件中
const {ref, insert, wrap} = useTextareaEditor();
return