原生 `
支持所有現代瀏覽器 (IE9+),API 簡潔強大:
function enableTabIndent(textarea, options = {}) {
const {tabSize = 4, useSpaces = true} = options;
const tabChar = useSpaces ? ' '.repeat(tabSize) : '\t';
textarea.addEventListener('keydown', (e) => {
if (e.key !== 'Tab') return;
// 處理輸入法組合狀態
if (e.isComposing || textarea.composing) return;
e.preventDefault(); // 阻止默認焦點切換
const {selectionStart, selectionEnd, value} = textarea;
const isSelection = selectionStart !== selectionEnd;
if (e.shiftKey) {
// Shift+Tab: 反向縮進 (刪除行首縮進)
if (isSelection) {
// 多行選區:批量去除行首縮進
const lines = value.substring(selectionStart, selectionEnd).split('\n');
let newText = lines.map(line =>
line.startsWith(tabChar) ? line.slice(tabChar.length) : line
).join('\n');
textarea.setRangeText(newText, selectionStart, selectionEnd, 'select');
} else {
// 單行:刪除光標前的縮進
const lineStart = value.lastIndexOf('\n', selectionStart - 1) + 1;
const beforeCursor = value.substring(lineStart, selectionStart);
if (beforeCursor.startsWith(tabChar)) {
textarea.setRangeText('', lineStart, lineStart + tabChar.length);
}
}
} else {
// Tab: 縮進
if (isSelection) {
// 多行選區:批量添加行首縮進
const lines = value.substring(selectionStart, selectionEnd).split('\n');
const newText = lines.map(line => tabChar + line).join('\n');
textarea.setRangeText(newText, selectionStart, selectionEnd, 'select');
} else {
// 單行:插入縮進字符
textarea.setRangeText(tabChar, selectionStart, selectionEnd, 'end');
}
}
});
}
// 使用
const textarea = document.getElementById('codeEditor');
enableTabIndent(textarea, {tabSize: 4, useSpaces: true});
textarea.setRangeText(replacement, start, end, selectMode);
// selectMode: 'start' | 'end' | 'select' | 'preserve'
// 'end' (默認): 光標移到插入文本後
// 'select': 選中插入的文本
// 'preserve': 盡量保持選區相對位置
class TextareaTabHandler {
constructor(textarea, options = {}) {
this.ta = textarea;
this.tabSize = options.tabSize || 4;
this.useSpaces = options.useSpaces !== false;
this.tabChar = this.useSpaces ? ' '.repeat(this.tabSize) : '\t';
this.composing = false;
this.bind();
}
bind() {
this.ta.addEventListener('compositionstart', () => this.composing = true);
this.ta.addEventListener('compositionend', () => this.composing = false);
this.ta.addEventListener('keydown', this.onKeyDown.bind(this));
}
onKeyDown(e) {
if (this.composing || e.key !== 'Tab') return;
e.preventDefault();
const {selectionStart: start, selectionEnd: end, value} = this.ta;
const hasSelection = start !== end;
if (e.shiftKey) {
this.handleUnindent(start, end, value, hasSelection);
} else {
this.handleIndent(start, end, value, hasSelection);
}
}
handleIndent(start, end, value, hasSelection) {
if (hasSelection) {
// 多行縮進
const lines = value.slice(start, end).split('\n');
const newText = lines.map(l => this.tabChar + l).join('\n');
this.ta.setRangeText(newText, start, end, 'select');
} else {
// 單點插入
this.ta.setRangeText(this.tabChar, start, end, 'end');
}
}
handleUnindent(start, end, value, hasSelection) {
if (hasSelection) {
// 多行反向縮進
const lines = value.slice(start, end).split('\n');
const newText = lines.map(l =>
l.startsWith(this.tabChar) ? l.slice(this.tabChar.length) : l
).join('\n');
this.ta.setRangeText(newText, start, end, 'select');
} else {
// 單行刪除行首縮進
const lineStart = value.lastIndexOf('\n', start - 1) + 1;
const linePrefix = value.slice(lineStart, start);
if (linePrefix.startsWith(this.tabChar)) {
this.ta.setRangeText('', lineStart, lineStart + this.tabChar.length);
}
}
}
destroy() {
this.ta.removeEventListener('keydown', this.onKeyDown);
this.ta.removeEventListener('compositionstart', () => this.composing = true);
this.ta.removeEventListener('compositionend', () => this.composing = false);
}
}
<script setup>
import { directive } from 'vue';
export const vTabIndent = {
mounted(el, binding) {
el._tabHandler = new TextareaTabHandler(el, binding.value);
},
unmounted(el) {
el._tabHandler?.destroy();
}
};
</script>
<textarea v-tab-indent="{tabSize: 2, useSpaces: true}"></textarea>
function useTabIndent(ref, options) {
useEffect(() => {
if (!ref.current) return;
const handler = new TextareaTabHandler(ref.current, options);
return () => handler.destroy();
}, [ref, options]);
}
// 使用
const textareaRef = useRef(null);
useTabIndent(textareaRef, {tabSize: 4});
return ;
| 問題 | 原因 | 解決 |
|---|---|---|
| 輸入法組合中按 Tab 亂碼 | 未檢查 isComposing | 監聽 compositionstart/end 設置標誌 |
| 光標位置錯誤 | 手動設置 selectionStart/End | 使用 setRangeText 最後參數 'end'/'select' |
| 撤銷/重做 (Ctrl+Z) 失效 | 直接修改 value 破壞歷史棧 | setRangeText 原生支持撤銷棧 |
| 大文本性能 | value 字符串操作 | 僅操作選區範圍,避免整文本處理 |
| 無障礙:Tab 導航失效 | 全局攔截 Tab | 只在 textarea focus 時攔截,或提供快捷鍵切換模式 |
現代瀏覽器原生 `setRangeText` + `selectionStart/End` 完美解決 Textarea Tab 縮進問題,代碼量 < 50 行,支持選區多行操作、Shift+Tab 反向縮進、撤銷棧、輸入法兼容。棄用老舊 `document.selection` / `createRange` IE 專有 API,拥抱標準 Web API。