contains与compareDocumentPosition方法详解

1. nodeA.contains(nodeB):
这个方法起先用在 IE ,用来确定nodeB是否包含在另一个nodeA中。
注意点:如果nodeA和nodeB相一致,.contains() 将返回 true ,虽然,一个元素不能包含自己。

2、nodeA.compareDocumentPosition(nodeB):
这个方法这个方法是 DOM Level 3 specification 的一部分,比contains方法强大得多,可以比较两个元素的相对位置,返回结果如下:
Bits Number Meaning
000000 0 元素一致
000001 1 节点在不同的文档(或者一个在文档之外)
000010 2 节点 B 在节点 A 之前
000100 4 节点 A 在节点 B 之前
001000 8 节点 B 包含节点 A
010000 16 节点 A 包含节点 B
100000 32 浏览器的私有使用
对于第一列代表的意思,可能很多同学以前不太了解,比特码可以将多个状态按位存储成一个数字,而多个状态是相互独立的,例如:
<div id="a">
<div id="b"></div>
</div>
<script>
alert( document.getElementById("a").compareDocumentPosition(document.getElementById("b")) == 20);
</script>
一旦一个节点 A 包含另一个节点 B,包含 B(+16) 且在 B 之前(+4),则最后的结果是数字 20 。如果你查看比特发生的变化,将增加你的理解。
000100 (4) + 010000 (16) = 010100 (20)

3.contains和compareDocumentPosition各浏览器差异:

IE6/7/8

IE9

Firefox

Safari

Chrome

Opera

contains

Y

Y

N

Y

Y

Y

compareDocumentPosition

N

Y

Y

Y

Y

Y



4.兼容IE的compareDocumentPosition实现:
// Compare Position - MIT Licensed, John Resig
function comparePosition(a, b){
return a.compareDocumentPosition ?
a.compareDocumentPosition(b) :
a.contains ?
( a != b && a.contains(b) && 16 ) +
( a != b && b.contains(a) && 8 ) +
( a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
(a.sourceIndex < b.sourceIndex && 4 ) +
(a.sourceIndex > b.sourceIndex && 2 ) :
1 ) :
0;
}


5.应用:

PPK 提供了一个关于通过创建一个 getElementsByTagNames 方法使新功能可以被使用的很棒的例子:

// Original by PPK quirksmode.org
function getElementsByTagNames(list, elem) {
elem = elem || document;
var tagNames = list.split(’,’), results = [];
for ( var i = 0; i < tagNames.length; i++ ) {
var tags = elem.getElementsByTagName( tagNames[i] );
for ( var j = 0; j < tags.length; j++ )
results.push( tags[j] );
}
return results.sort(function(a, b){
return 3 - (comparePosition(a, b) & 6);
});
}

我们现在可以使用他来按次序构建一个站点的目录:getElementsByTagNames("h1, h2, h3");


http://msdn.microsoft.com/en-us/library/ms536377%28VS.85%29.aspx

https://developer.mozilla.org/En/DOM/Node.compareDocumentPosition

http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition

http://ejohn.org/blog/comparing-document-position/




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值