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

瀏覽器相容性

另見