不同瀏覽器獲取/設置光標位置的 API 歷史上差異巨大:
$.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();
}
}
});
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}); // 插入並選中
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)'));
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);
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 ;
if (!HTMLTextareaElement.prototype.setRangeText) {
HTMLTextareaElement.prototype.setRangeText = function(text, start, end, selectMode) {
// 簡易 Polyfill 僅支持基本插入
if (typeof start === 'undefined') start = this.selectionStart;
if (typeof end === 'undefined') end = this.selectionEnd;
const val = this.value;
this.value = val.slice(0, start) + text + val.slice(end);
const newPos = start + text.length;
if (selectMode === 'select') {
this.setSelectionRange(start, newPos);
} else {
this.setSelectionRange(newPos, newPos);
}
};
}
現代瀏覽器**原生 `setRangeText` 完美解決**光標位置插入文本問題,代碼量 < 10 行,支持選區替換、光標定位、撤銷棧、滾動保持。原文的 jQuery 插件雖兼容 IE 老版本,但代碼冗長、邏輯脆弱。新項目**直接使用原生 API**,老項目可引入輕量 Polyfill。封裝 `TextareaEditor` 類可復用構建 Markdown 編輯器、代碼片段插入等豐富功能。