IE有许多好用的方法,后来都被其他浏览器抄袭了,比如这个contains方法。如果A元素包含B元素,则返回true,否则false。唯一不支持这个方法的是IE的死对头firefox。
提示:你可以先修改部分代码再运行。
不过火狐支持compareDocumentPosition() 方法,这是W3C制定的方法,标准浏览器都支持,不过实用性性很差,因此没有什么人用,推广不开来。它的使用形式与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 | 浏览器的私有使用 |
提示:你可以先修改部分代码再运行。
PPK给出如下解决方法。
if (window.Node && Node.prototype && !Node.prototype.contains){
Node.prototype.contains = function (arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
我搞出个更短的:
if(!!window.find){
HTMLElement.prototype.contains = function(B){
return this.compareDocumentPosition(B) - 19 > 0
}
}
提示:你可以先修改部分代码再运行。
descendantOf: function(element, ancestor) {
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) &
=== 8;
if (ancestor.contains)
return ancestor.contains(element) && ancestor !== element;
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
原文地址:http://www.cnblogs.com/rubylouvre/archive/2011/05/30/1583523.html