Selection: setPosition() 方法

Baseline 已广泛支持

此功能已成熟,并且可在许多设备和浏览器版本中正常工作。自 ⁨2017 年 8 月⁩ 起在浏览器中可用。

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

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

语法

js
setPosition(node)
setPosition(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().setPosition(body, 0);

规范

规范
Selection API
# dom-selection-collapse

浏览器兼容性

另见