Selection: containsNode() 方法
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 |
瀏覽器相容性
載入中…
另見
Selection,它所屬的介面。