From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../api/node/comparedocumentposition/index.html | 127 +++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 files/zh-cn/web/api/node/comparedocumentposition/index.html (limited to 'files/zh-cn/web/api/node/comparedocumentposition') diff --git a/files/zh-cn/web/api/node/comparedocumentposition/index.html b/files/zh-cn/web/api/node/comparedocumentposition/index.html new file mode 100644 index 0000000000..e1b0adf99b --- /dev/null +++ b/files/zh-cn/web/api/node/comparedocumentposition/index.html @@ -0,0 +1,127 @@ +--- +title: Node.compareDocumentPosition +slug: Web/API/Node/compareDocumentPosition +tags: + - API + - DOM + - Method + - Node + - Position + - Reference + - 比较文档位置 +translation_of: Web/API/Node/compareDocumentPosition +--- +
{{ ApiRef("DOM") }}
+ +

Node.compareDocumentPosition() 可以比较当前节点与任意文档中的另一个节点的位置关系。

+ +

返回值是一个具有以下值的位掩码:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常量名十进制值含义
DOCUMENT_POSITION_DISCONNECTED1不在同一文档中
DOCUMENT_POSITION_PRECEDING2otherNode在node之前
DOCUMENT_POSITION_FOLLOWING4otherNode在node之后
DOCUMENT_POSITION_CONTAINS8otherNode包含node
DOCUMENT_POSITION_CONTAINED_BY16otherNode被node包含
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC32待定
+ +

语法

+ +
compareMask = node.compareDocumentPosition( otherNode )
+
+ +

参数

+ +
+
otherNode
+
用于比较位置的 Node 。
+
+ +

返回值

+ +

一个表示 NodeotherNode 在 {{domxref("Document")}} 中关系的整数值。在一些场景下,可能设置了不止一位比特值。比如 otherNode 在文档中是靠前的且包含了 Node, 那么DOCUMENT_POSITION_CONTAINSDOCUMENT_POSITION_PRECEDING 位都会设置,所以结果会是 0x0A 即十进制下的 10。

+ +

例子

+ +
var head = document.getElementsByTagName('head').item(0);
+if (head.compareDocumentPosition(document.body) & Node.DOCUMENT_POSITION_FOLLOWING) {
+  console.log("well-formed document");
+} else {
+  console.log("<head> is not before <body>");
+}
+
+ +
+

注: 因为compareDocumentPosition返回的是一个位掩码,所以必须再使用按位与运算符才能得到有意义的值.

+
+ +

注意第一条语句使用了带有参数 0 的 {{domxref("NodeList.item()")}} 方法,它和 getElementsByTagName('head')[0] 是一样的。

+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范状态注释
{{SpecName('DOM WHATWG','#dom-node-comparedocumentposition','Node.compareDocumentPosition()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM3 Core','core.html#Node3-compareDocumentPosition','Node.compareDocumentPosition()')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

浏览器兼容性

+ + + +

{{Compat("api.Node.compareDocumentPosition")}}

+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf