Selection: collapse() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Selection.collapse() 方法将当前选区折叠到单个点。文档不会被修改。如果内容处于聚焦状态且可编辑,光标将在此闪烁。

注意:此方法是 Selection.setPosition() 方法的别名。

语法

js
collapse(node)
collapse(node, offset)

参数

node

光标位置将在该节点内。此值也可以设置为 null — 如果指定了 null,则该方法将表现得如同 Selection.removeAllRanges(),即,所有范围都将从选区中移除。

offset 可选

选区将在 node 中的偏移量,折叠将发生在此。如果未指定,则使用默认值 0

返回值

无(undefined)。

示例

js
// Place the caret at the beginning of an HTML document's body.
const body = document.querySelector("body");
window.getSelection().collapse(body, 0);

规范

规范
Selection API
# dom-selection-collapse

浏览器兼容性

另见