為了相容IE和FF我們不得不用以下方法: <meta charset="utf-8"><meta name="keywords" content="dom contains方法 by 司徒正美"><meta name="description" content="dom contains方法 by 司徒正美"><br />contains方法<p><strong id="child">contains方法</strong></p><p>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
不過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 |
瀏覽器的私人使用 |
<meta charset="utf-8"><meta name="keywords" content="dom contains方法 by 司徒正美"><meta name="description" content="dom contains方法 by 司徒正美"><br />compareDocumentPosition方法<p><strong id="child">本例子請在標準瀏覽器中運行。</strong></p><p>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
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
}
}
<meta charset="utf-8"><meta name="keywords" content="dom contains方法 by 司徒正美"><meta name="description" content="dom contains方法 by 司徒正美"><br />contains方法<p><strong id="child">contains方法</strong></p><p>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
複製代碼 代碼如下://2011.9.24 by 司徒正美
var contains = function(root, el) {
if (root.compareDocumentPosition)
return root === el || !!(root.compareDocumentPosition(el) & 16);
if (root.contains && el.nodeType === 1){
return root.contains(el) && root !== el;
}
while ((el = el.parentNode))
if (el === root) return true;
return false;
}