js contains方法实现代码


为了兼容IE和FF我们不得不用以下方法:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

不过火狐支持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 浏览器的私有使用

[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
}
}


[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;
}

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3