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

浏览器兼容性

另见