实现说明
全部逻辑都在函数 syncToolbar中。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。
常见问题
「selectionchange 追踪输入框选区边界」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。
主签名形如 function syncToolbar()
核心语句
document.addEventListener('selectionchange', () => {
if (document.activeElement === editor) syncToolbar();
});
const start = editor.selectionStart ?? 0;
const end = editor.selectionEnd ?? 0;
代码示例
const editor = document.querySelector('textarea') as HTMLTextAreaElement;
const formatBar = document.querySelector('.format-bar') as HTMLElement;
function syncToolbar(): void {
const start = editor.selectionStart ?? 0;
const end = editor.selectionEnd ?? 0;
const selected = editor.value.slice(start, end);
formatBar.classList.toggle('selection-active', end > start);
console.log(end > start ? `selected ${selected.length} chars` : 'collapsed caret');
}
// selectionchange fires on the document for every caret or selection move,
// so the active element decides whose selection changed.
document.addEventListener('selectionchange', () => {
if (document.activeElement === editor) syncToolbar();
});
syncToolbar();