Selection:empty() 方法

Baseline 已廣泛支援

此功能已成熟,並且可在許多裝置和瀏覽器版本中正常工作。自 ⁨2017 年 8 月⁩ 起在瀏覽器中可用。

Selection.empty() 方法會移除 selection 中的所有 range,將 anchorNodefocusNode 屬性設定為 null,並且不進行任何 selection。當呼叫此方法時,會在 document 上觸發一個 selectionchange 事件。

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

語法

js
empty()

引數

無。

返回值

無(undefined)。

示例

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

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.empty();
});

規範

規範
Selection API
# dom-selection-removeallranges

瀏覽器相容性

另見