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

瀏覽器相容性

另見