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

瀏覽器相容性

另見