萬盛學電腦網

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

JavaScript 獲取與設置 Textarea/Input 光標位置:跨瀏覽器兼容方案

核心 API 對比

場景現代標準 APIIE 兼容方案
獲取光標位置 element.selectionStart document.selection.createRange() + TextRange 計算
設置光標位置 element.setSelectionRange(start, end) element.createTextRange() + moveStart/moveEnd/select
獲取選中文本 element.value.substring(s, e) document.selection.createRange().text

通用工具函數(兼容 IE9+ 及現代瀏覽器)


/**
 * 獲取輸入框光標位置(選區起始)
 * @param {HTMLInputElement|HTMLTextAreaElement} el
 * @returns {number} 光標位置(0-based)
 */
function getCursorPosition(el) {
  el.focus(); // 確保焦點
  
  // 現代瀏覽器
  if (typeof el.selectionStart === 'number') {
    return el.selectionStart;
  }
  
  // IE ≤ 8/9 (document.selection)
  if (document.selection) {
    const range = document.selection.createRange();
    if (!range) return el.value.length; // 無選區時返回末尾
    
    const textRange = el.createTextRange();
    const duplicate = textRange.duplicate();
    
    textRange.moveToBookmark(range.getBookmark());
    duplicate.setEndPoint('EndToStart', textRange);
    
    return duplicate.text.length;
  }
  
  return el.value.length; // 兜底
}

/**
 * 設置輸入框光標位置(可同時設置選區)
 * @param {HTMLInputElement|HTMLTextAreaElement} el
 * @param {number} start 起始位置
 * @param {number} [end=start] 結束位置,默認同 start(無選區)
 */
function setCursorPosition(el, start, end = start) {
  el.focus();
  
  // 現代瀏覽器
  if (el.setSelectionRange) {
    el.setSelectionRange(start, end);
    return;
  }
  
  // IE ≤ 8/9
  if (el.createTextRange) {
    const range = el.createTextRange();
    range.collapse(true);           // 移動到開頭
    range.moveEnd('character', end);   // 移動結束點
    range.moveStart('character', start); // 移動起始點
    range.select();
  }
}

實戰應用場景

1. @提及/表情插入:在光標處插入內容


function insertAtCursor(el, text) {
  const pos = getCursorPosition(el);
  const val = el.value;
  el.value = val.slice(0, pos) + text + val.slice(pos);
  setCursorPosition(el, pos + text.length); // 光標移至插入內容後
}

// 使用
$('#editor').on('click', '.emoji-btn', function() {
  insertAtCursor(document.getElementById('editor'), $(this).data('emoji'));
});

2. 即時字數統計與限制


$('#textarea').on('input', function() {
  const max = 140;
  const len = this.value.length;
  $('#counter').text(`${len}/${max}`);
  
  if (len > max) {
    // 截斷並保持光標在末尾
    this.value = this.value.slice(0, max);
    setCursorPosition(this, max);
  }
});

3. 代碼編輯器:Tab 鍵插入縮進而非切換焦點


$('#code-editor').on('keydown', function(e) {
  if (e.key === 'Tab') {
    e.preventDefault();
    insertAtCursor(this, '  '); // 兩空格縮進
  }
});

4. 選中文本獲取與操作


function getSelectedText(el) {
  const start = getCursorPosition(el);
  const end = el.selectionEnd || start; // IE 無 selectionEnd,近似處理
  return el.value.slice(start, end);
}

function wrapSelection(el, prefix, suffix) {
  const start = getCursorPosition(el);
  const end = el.selectionEnd || start;
  const selected = el.value.slice(start, end);
  if (!selected) return;
  
  const wrapped = prefix + selected + suffix;
  el.value = el.value.slice(0, start) + wrapped + el.value.slice(end);
  setCursorPosition(el, start, start + wrapped.length); // 保持選中狀態
}

// 使用:Ctrl+B 加粗 Markdown
$('#editor').on('keydown', function(e) {
  if (e.ctrlKey && e.key === 'b') {
    e.preventDefault();
    wrapSelection(this, '**', '**');
  }
});

現代 Selection API(更強大、標準化)


// 獲取選區(輸入框內)
const selection = document.getSelection(); // 全局選區
// 或
const range = el.ownerDocument.getSelection().getRangeAt(0); // 需先 focus

// 設置選區
const range = document.createRange();
range.setStart(el.firstChild, offset);
range.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

注意:Selection API 主要用於 contenteditable 富文本編輯器,input/textarea 仍建議用 selectionStart/End + setSelectionRange,API 更簡潔穩定。

常見坑點

  • 未 focus 先調用:selectionStart 在無焦點時可能返回 0 或拋錯,始終先 el.focus()。
  • 隱藏元素(display:none):無法獲取/設置選區,需臨時顯示或用 visibility:hidden 替代。
  • IE 虛擬選區:document.selection.createRange() 返回的是文檔級選區,需用 moveToBookmark 映射到輸入框。
  • 插入內容後光標位置:插入文本後需手動 setCursorPosition(el, newPos),否則光標停留原位。
  • Android 某些 WebView:selectionStart 可能不可靠,需結合 setTimeout 延遲讀取。

封裝建議:輕量級工具庫


// cursor.js
export const cursor = {
  get(el) { /* ... */ },
  set(el, start, end) { /* ... */ },
  getSelection(el) { /* 返回 {start, end, text} */ },
  replaceSelection(el, text) { /* 替換選區內容 */ },
  wrapSelection(el, prefix, suffix) { /* 包裹選區 */ }
};

// 使用
import { cursor } from './cursor';
cursor.wrapSelection(textarea, '**', '**');

總結

獲取/設置光標位置是構建富文本編輯器、@提及、代碼編輯器、即時驗證等交互的基石。現代瀏覽器統一支持 selectionStart/End + setSelectionRange,IE 兼容需額外處理 TextRange。封裝通用工具函數,統一處理焦點、邊界、選區邏輯,能讓業務代碼保持清晰、健壯。

copyright © 萬盛學電腦網 all rights reserved