这是 实验性技术
检查 浏览器兼容性表格 要小心谨慎在生产中使用这之前。

Selection.containsNode() method indicates whether a specfied node is part of the selection.

句法

sel.containsNode(node, partialContainment)
					

参数

node

The node that is being looked for in the selection.

partialContainment 可选
true , containsNode() 返回 true when a part of the node is part of the selection. When false , containsNode() only returns true when the entire node is part of the selection. If not specified, the default value false 被使用。

范例

Check for selection

This snippet checks whether anything inside the body element is selected.

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

Find the hidden word

In this example, a message appears when you select the secret word. It uses addEventListener() to check for selectionchange 事件。

HTML

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

JavaScript

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);
});
					

结果

规范

规范 状态 注释
选定 API
The definition of 'Selection.containsNode()' in that specification.
工作草案 Current

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
containsNode Chrome Yes Edge 12 Firefox 4
4
Before Firefox 35, the method didn't throw if node was null .
IE No Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4
4
Before Firefox 35, the method didn't throw if node was null .
Opera Android Yes Safari iOS Yes Samsung Internet Android Yes
partialContainment parameter is optional Chrome Yes Edge ≤79 Firefox 55 IE No Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 55 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

不支持

不支持

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

见实现注意事项。

另请参阅

元数据

  • 最后修改: