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”和“的元素
第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;
}
以上就是HTML DOM compareDocumentPosition() 方法
比较文档位置的详细内容,更多请关注双恒网络其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。



