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

PHPz
发布: 2023-09-14 19:21:10
转载
1425人浏览过

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() 方法

比较文档位置

在上面的示例中 -

Calliper 文档对比神器
Calliper 文档对比神器

文档内容对比神器

Calliper 文档对比神器 28
查看详情 Calliper 文档对比神器

我们首先创建了两个 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() 方法 比较文档位置的详细内容,更多请关注php中文网其它相关文章!

相关标签:
HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号