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