javascript contains方法
IE有许多好用的方法,后来都被其他浏览器抄袭了,比如这个contains方法。如果A元素包含B元素,则返回true,否则false。唯一不支持这个方法的是IE的死对头firefox。
给出如下解决方法。
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
}
}
<!doctype html><title>dom contains 方法 by youyou</title><meta charset="utf-8"/><meta name="keywords" content="dom contains方法 by youyou" /><meta name="description" content="dom contains方法 by youyou" /><script type="text/javascript"> if(!!window.find){ HTMLElement.prototype.contains = function(B){ return this.compareDocumentPosition(B) - 19 > 0 } } window.onload = function(){ var A = document.getElementById('parent'), B = document.getElementById('child'); alert(A.contains(B)); alert(B.contains(A)); }</script><h2 style="text-align:center">contains方法</h2><div id="parent"> <p> <strong id="child" >contains方法</strong> </p></div>
if(typeof(HTMLElement)!="undefined"){HTMLElement.prototype.contains=function(obj){while(obj!=null&&typeof(obj.tagName)!="undefind"){if(obj==this){return true;}obj=obj.parentNode;}return false;};}function hideBox(event){event=event||window.event;if(event){var isIE = /msie/i.test(navigator.userAgent);if (isIE){if(document.getElementById('stateList').contains(event.toElement)){ return; }}else{if(document.getElementById('stateList').contains(event.relatedTarget)){ return; }}}$('#stateList').hide();}