首页 > 文章列表 > HTML DOM compareDocumentPosition() 方法 比较文档位置

HTML DOM compareDocumentPosition() 方法 比较文档位置

342 2023-09-16

HTML DOM CompareDocumentPosition() 方法用于将给定节点位置与任何文档中的任何其他节点进行比较。该方法的返回类型是整数类型,用于描述它们在文档中的位置。整数返回值如指定 -

1: No relationship, the two nodes do not belong to the same document.
2: The first node (para1) is positioned after the second node (para2).
4: The first node (para1) is positioned before the second node (para2).
8: The first node (para1) is positioned inside the second node (para2).
16: The second node (para2) is positioned inside the first node (para1).
32: No relationship, or the two nodes are two attributes on the same element.

语法

以下是 HTML DOM CompareDocumentPosition() 方法的语法 -

node.compareDocumentPosition(node)

这里的节点是节点对象类型,指定我们要与当前节点进行比较的节点。

示例

让我们看一个compareDocumentPosition的示例() 方法 -

<!DOCTYPE html>
<html>
<body>
<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>
<p>Click the button to compare the position of the two paragraphs.</p>
<button onclick="docPosition()">POSITION</button>
<p id="Sample"></p>
<script>
   function docPosition() {
      var p1 = document.getElementById("para1").lastChild;
      var p2 = document.getElementById("para2").lastChild;
      var x = p2.compareDocumentPosition(p1);
      document.getElementById("Sample").innerHTML = x;
   }
</script>
</body>
</html>

输出

这将产生以下输出 -

HTML DOM compareDocumentPosition() 方法

比较文档位置

单击“位置”按钮时 -

HTML DOM compareDocumentPosition() 方法

比较文档位置

在上面的示例中 -

我们首先创建了两个 id 为“para1”和“的元素

第2段”。

<p id="para1">This is a paragraph</p>
<p id="para2">This is another paragraph</p>

然后我们创建了一个按钮 POSTION,它将在用户单击时执行 docPosition() 方法 -

<button onclick="docPosition()">POSITION</button>

docPosition() 方法使用文档对象上的 getElementById() 方法获取 <p> 元素。然后,它将两个段落的lastchild 属性值分别赋给变量p1 和p2。

然后,我们以p1 作为参数,调用p2 上的compareDocumentPosition() 方法。这意味着我们要比较 p2 相对于 p1 的位置。由于这里 p2 位于 p1 之后,因此返回值为 2 -

function docPosition() {
   var p1 = document.getElementById("para1").lastChild;
   var p2 = document.getElementById("para2").lastChild;
   var x = p2.compareDocumentPosition(p1);
   document.getElementById("Sample").innerHTML = x;
}