Concept list
Lib
Selecion 和 Range
| 概念 |
说明 |
Selection |
表示用户当前“选中了什么”的对象,是浏览器提供的接口。通过 window.getSelection() 获取。 |
Range |
描述“从哪到哪”的精确范围对象,是底层数据结构。用于实际操作 DOM。 |
🔗 Selection 持有 Range,Range 定义选区内容
Selection 是“容器”或“视图” → 用户看到的高亮
Range 是“数据”或“工具” → 程序用来操作的内容
- 一个
Selection 可以包含多个 Range(但大多数浏览器只支持一个)
💡 不是 Selection 创建 Range,而是:
- 用户操作 → 浏览器创建
Range → 放入 Selection
- 程序创建
Range → 手动加入 Selection
| 属性 |
说明 |
anchorNode / anchorOffset |
选区起点(用户开始拖动的位置) |
focusNode / focusOffset |
选区终点(用户松开鼠标的位置) |
isCollapsed |
是否“折叠”(即光标闪烁,无内容被选中) |
rangeCount |
包含多少个 Range(通常是 1) |
type |
类型:"None"、"Caret"(光标)、"Range"(有内容) |
| 方法 |
作用 |
getRangeAt(index) |
获取第 index 个 Range(最常用!) |
removeAllRanges() |
清除所有选区(取消高亮) |
addRange(range) |
将一个 Range 加入选区(让用户看到) |
deleteFromDocument() |
删除选中的内容 |
collapse(node, offset) |
折叠成光标,定位到某位置 |
selectAllChildren(node) |
选中某个节点的所有子内容 |
| 属性 |
说明 |
startContainer |
起点所在的节点(通常是文本节点或元素) |
startOffset |
起点在 startContainer 中的偏移量 |
endContainer |
终点所在的节点 |
endOffset |
终点在 endContainer 中的偏移量 |
| 方法 |
作用 |
cloneContents() |
复制选中的 DOM 片段(包含标签、属性、id、class 等) |
extractContents() |
移除并返回 DOM 片段 |
deleteContents() |
删除选中内容 |
insertNode(node) |
在选区起点插入一个节点(如图片) |
surroundContents(newNode) |
用新节点包裹选中内容(如加粗) |
cloneRange() |
复制一个 Range |
1 2
| const selection = window.getSelection(); console.log(selection.toString());
|
- ✅ 获取用户选中内容(完整 DOM,含 id/class)
1 2 3 4 5 6
| const selection = window.getSelection(); if (selection.rangeCount > 0) { const range = selection.getRangeAt(0); const fragment = range.cloneContents(); console.log(fragment); }
|
- ✅ 程序控制选区(自动高亮某段)
1 2 3 4 5 6
| const range = document.createRange(); range.selectNode(someElement);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
|
- ✅ 插入图片到光标处
1 2 3 4 5 6 7 8
| const img = document.createElement('img'); img.src = 'emoji.png';
const selection = window.getSelection(); if (selection.rangeCount > 0) { const range = selection.getRangeAt(0); range.insertNode(img); }
|
- ✅ 加粗选中文字
1 2 3 4 5 6
| const selection = window.getSelection(); if (selection.rangeCount > 0 && !selection.isCollapsed) { const range = selection.getRangeAt(0); const strong = document.createElement('strong'); range.surroundContents(strong); }
|