Selection: removeAllRanges() 方法
Selection.removeAllRanges() 方法会移除选区中的所有范围,并将 anchorNode 和 focusNode 属性设置为 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 |
浏览器兼容性
加载中…