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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值