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,它所属的接口。