js实现选区
选区操作基础概念
选区(Selection)指用户在页面上通过鼠标或键盘选中的文本范围,可通过 JavaScript 操作。核心对象是 Selection 和 Range,前者表示用户选择的区域,后者表示具体的文档片段范围。
获取当前选区
通过 window.getSelection() 获取选区对象,返回 Selection 实例:
const selection = window.getSelection();
// 检查是否有选中内容
if (selection.toString().length > 0) {
console.log("选中文本:", selection.toString());
}
创建自定义选区
通过 Range 和 Selection 结合实现:
const paragraph = document.getElementById("myText");
const range = document.createRange();
range.selectNodeContents(paragraph); // 选中段落内容
const selection = window.getSelection();
selection.removeAllRanges(); // 清除现有选区
selection.addRange(range); // 添加新选区
选区边界控制
通过 setStart 和 setEnd 精确控制选区范围:
const textNode = document.querySelector("#myText").firstChild;
const range = document.createRange();
range.setStart(textNode, 5); // 从第5个字符开始
range.setEnd(textNode, 10); // 到第10个字符结束
window.getSelection().addRange(range);
选区内容修改
通过 deleteContents() 或 extractContents() 操作选区内容:
const selection = window.getSelection();
const range = selection.getRangeAt(0);
range.deleteContents(); // 删除选中内容
// 或提取内容到文档片段
const fragment = range.extractContents();
document.body.appendChild(fragment);
插入内容到选区
使用 insertNode 或 surroundContents:
const range = window.getSelection().getRangeAt(0);
const newNode = document.createElement("span");
newNode.textContent = "插入的内容";
range.insertNode(newNode);
// 包裹选区内容
const wrapper = document.createElement("strong");
range.surroundContents(wrapper);
兼容性注意事项
- 旧版 IE 使用
document.selection而非window.getSelection()。 - 操作前需检查选区是否存在(
selection.rangeCount > 0)。
实际应用示例
高亮选中文本的完整代码:
document.addEventListener("mouseup", () => {
const selection = window.getSelection();
if (selection.toString().length > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement("span");
span.className = "highlight";
range.surroundContents(span);
selection.removeAllRanges();
}
});
CSS 样式:

.highlight { background-color: yellow; }
通过上述方法可实现动态选区操作,适用于富文本编辑、标注等场景。






