Selection: containsNode() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Selection.containsNode() 方法指示指定的節點是否是選區的一部分。

語法

js
containsNode(node)
containsNode(node)
containsNode(node, partialContainment)

引數

node

要在選區中查詢的節點。

partialContainment 可選

當設定為 true 時,如果節點的某一部分是選區的一部分,containsNode() 將返回 true。當設定為 false 時,只有當整個節點都是選區的一部分時,containsNode() 才返回 true。如果未指定,則使用預設值 false

返回值

如果給定節點是選區的一部分,則返回 true,否則返回 false

示例

檢查選區

此程式碼片段檢查 body 元素內的任何內容是否被選中。

js
console.log(window.getSelection().containsNode(document.body, true));

查詢隱藏的單詞

在此示例中,當您選中秘密單詞時,會顯示一條訊息。它使用 addEventListener() 來檢查 selectionchange 事件。

HTML

html
<p>Can you find the secret word?</p>
<p>Hmm, where <span id="secret">SECRET</span> could it be?</p>
<p id="win" hidden>You found it!</p>

CSS

css
#secret {
  color: transparent;
}

JavaScript

js
const secret = document.getElementById("secret");
const win = document.getElementById("win");

// Listen for selection changes
document.addEventListener("selectionchange", () => {
  const selection = window.getSelection();
  const found = selection.containsNode(secret);

  win.toggleAttribute("hidden", !found);
});

結果

規範

規範
Selection API
# dom-selection-containsnode

瀏覽器相容性

另見