案例:javascript案例     状态:可编辑再运行    进入竖版
 运行结果 
x
 
1
<!DOCTYPE html>
2
<html>
3
<body>
4
5
<p id="p1">This is a paragraph</p>
6
<p id="p2">This is another paragraph</p>
7
8
<p id="demo">请点击按钮来比较两个段落的位置。</p>
9
10
<button onclick="myFunction()">试一下</button>
11
12
<script>
13
function myFunction()
14
{
15
var p1=document.getElementById("p1").lastChild;
16
var p2=document.getElementById("p2").lastChild;
17
var x=document.getElementById("demo");
18
x.innerHTML=p1.compareDocumentPosition(p2);
19
}
20
</script>
21
22
<p>
23
1: The two nodes do not belong to the same document.<br>
24
2: p1 is positioned after p2.<br>
25
4: p1 is positioned before p2.<br>
26
8: p1 is positioned inside p2.<br>
27
16: p2 is positioned inside p1.<br>
28
32: The two nodes has no relationship, or they are two attributes on the same element.
29
</p>
30
31
<p><b>注释:</b>Internet Explorer 8 以及更早的版本不支持此方法。</p>
32
33
<p><b>注释:</b>返回值可以是值的组合。例如,返回 20 意味着在 p2 在 p1 内部(16),并且 p1 在 p2 之前(4)。</p>
34
35
</body>
36
</html>
37