兼容性阻止事件冒泡。
事件流:根据事件的传递顺序
冒泡:
事件由最具体的元素(文档中签到层次最深的节点)接收,逐级向上传播
到其他节点btn>div>body
现在浏览器默认都是冒泡排序。
捕获:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{width: 200px;height: 200px;background: skyblue;text-align: center;line-height: 200px;}
</style>
</head>
<body>
<div id="box">
<button id="btn">按钮</button>
</div>
</body>
<script type="text/javascript">
var o=document.getElementById('box');
var btn=document.getElementById('btn');
//给body加点击事件
document.body.onclick=function(){
alert('body');
};
//分别为div和按钮添加点击事件
o.onclick=function(e){
alert('div');
e.stopPropagation();//拦截事件传递
};
btn.onclick=function(e){//事件对象
alert('button');
//兼容性写法阻止事件冒泡
e?e.stopPropagation():window.event.cancelBubble=true;
};
</script>
</html>
注释:
在IE中获取事件对象是通过 var e=window.event;如果用参数则找不到事件对象,undefined ;
在谷歌和火狐用参数接收就能找到事件对象。 比IE的方法节省内存
谷歌和火狐阻止冒泡的方法 :e.stopPropagation();
IE阻止冒泡的方法:e.cancelBubble=true ;
这两种如果都写的话则会出现错误。 用兼容性方法可以提高效率。
e?e.stopPropagation():window.event.cancelBubble=true;
e 如果为真则是能找到事件对象(谷歌,火狐),执行e.stopPropagation();阻止冒泡
e 如果是undefined为假,(IE)则找不到事件对象,执行window.event 找对象,对象 . cancelBubble=true ; 执行冒泡