Selection: removeAllRanges() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Selection.removeAllRanges() 方法會移除選區中的所有範圍,並將 anchorNodefocusNode 屬性設定為 null,此時頁面上沒有任何被選中內容。呼叫此方法時,會在 document 上觸發一個 selectionchange 事件。

注意:此方法是 Selection.empty() 方法的別名。

語法

js
removeAllRanges()

引數

無。

返回值

無(undefined)。

示例

本示例透過監聽 document 上的 selectionchange 事件,來顯示頁面是否有選中內容。此外,還有一個按鈕,透過呼叫 Selection.removeAllRanges() 來清除任何選區。發生這種情況時,選區會發生變化,訊息也會隨之更新。

html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
js
const log = document.getElementById("log");

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.removeAllRanges();
});

規範

規範
Selection API
# dom-selection-removeallranges

瀏覽器相容性

另見