当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML DOM compareDocumentPosition()用法及代码示例


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>

输出

这将产生以下输出 -

单击位置按钮 -

在上面的例子中 -

我们首先创建了两个

id 为 “para1” 和 “para2” 的元素。

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

相关用法


注:本文由纯净天空筛选整理自AmitDiwan大神的英文原创作品 HTML DOM compareDocumentPosition() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。