Selection: deleteFromDocument() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Selection 接口的 deleteFromDocument() 方法会在选中的 Range 上调用 Range.deleteContents() 方法。

语法

js
deleteFromDocument()

参数

无。

返回值

无(undefined)。

示例

此示例允许您通过单击按钮来删除选定的文本和/或节点。单击按钮后,Window.getSelection() 方法会获取选中的内容,然后 deleteFromDocument() 方法将其删除。

HTML

html
<p>Try highlighting some of the elements in these paragraphs.</p>
<p>
  Once you do, you can remove the selected content by clicking the button below.
</p>
<h2>All of the selected text/nodes will be removed.</h2>
<button>Delete selected text</button>

JavaScript

js
let button = document.querySelector("button");
button.addEventListener("click", deleteSelection);

function deleteSelection() {
  let selection = window.getSelection();
  selection.deleteFromDocument();
}

结果

规范

规范
Selection API
# dom-selection-deletefromdocument

浏览器兼容性

另见