| 場景 | 現代標準 API | IE 兼容方案 |
|---|---|---|
| 獲取光標位置 | element.selectionStart |
document.selection.createRange() + TextRange 計算 |
| 設置光標位置 | element.setSelectionRange(start, end) |
element.createTextRange() + moveStart/moveEnd/select |
| 獲取選中文本 | element.value.substring(s, e) |
document.selection.createRange().text |
/**
* 獲取輸入框光標位置(選區起始)
* @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();
}
}
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'));
});
$('#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);
}
});
$('#code-editor').on('keydown', function(e) {
if (e.key === 'Tab') {
e.preventDefault();
insertAtCursor(this, ' '); // 兩空格縮進
}
});
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, '**', '**');
}
});
// 獲取選區(輸入框內)
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 更簡潔穩定。
selectionStart 在無焦點時可能返回 0 或拋錯,始終先 el.focus()。visibility:hidden 替代。document.selection.createRange() 返回的是文檔級選區,需用 moveToBookmark 映射到輸入框。setCursorPosition(el, newPos),否則光標停留原位。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。封裝通用工具函數,統一處理焦點、邊界、選區邏輯,能讓業務代碼保持清晰、健壯。