文本选择工具栏

使用 CSS Anchor Positioning 实现类似 Medium 的文本选择工具栏,选中文本时自动显示格式化选项。

核心特性

1. 选区检测

使用 window.getSelection() API 检测文本选择:

const handleSelection = () => {
  const selection = window.getSelection();
  if (selection && selection.toString().trim()) {
    const range = selection.getRangeAt(0);
    setSelectionRect(range.getBoundingClientRect());
    setShowToolbar(true);
  }
};

2. 动态锚点

因为选区位置是动态的,需要创建一个隐藏的锚点元素:

<span
  style={{
    anchorName: '--selection-anchor',
    left: selectionRect.left + selectionRect.width / 2,
    top: selectionRect.top,
  }}
/>

3. 工具栏定位

工具栏定位到选区上方中央:

style={{
  positionAnchor: '--selection-anchor',
  bottom: 'anchor(top)',
  left: 'anchor(center)',
  translate: '-50% -8px',
  positionTryFallbacks: 'flip-block',
}}

4. 自动翻转

当选区在页面顶部时,工具栏会自动翻转到选区下方显示(通过 flip-block)。

实现要点

  • 监听 mouseup 事件检测文本选择
  • 使用 getBoundingClientRect() 获取选区位置
  • 创建隐藏的锚点元素作为定位参考
  • 工具栏包含常用的文本格式化操作
  • 点击工具栏按钮不会导致选区消失

应用场景

  • 富文本编辑器
  • 在线文档协作工具
  • 内容管理系统
  • 笔记应用