阻止事件冒泡 - e.stopPropagation()
事件冒泡介绍
事件冒泡:开始时由具体的元素接收,然后逐级向上传播到DOM最顶层节点。
事件冒泡本身的特性,会带来的坏处,也会带来的好处,需要我们灵活掌握。
事件冒泡示例及效果图:
效果图中我是点击了son盒子,触发冒泡事件,father盒子和document也都被触发事件。这在开发中我们有时是不希望出现的。
例如我们想勾选购物车内的商品,但是我们并不希望又进入商品的详情页(此处用户需求是仅仅勾选商品),此时我们就需要阻止事件冒泡。
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15-阻止事件冒泡</title>
<style>
.father {
margin: 10px auto;
width: 150px;
height: 150px;
background-color: blueviolet;
position: relative;
cursor:pointer;
}
.son {
width: 80px;
height: 80px;
background-color: pink;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
text-align: center;
line-height: 80px;
cursor:pointer;
}
</style>
</head>
<body>
<div class="father">
<div class="son">son</div>
</div>
<script>
var divs = document.querySelectorAll('div')
// 父div注册绑定事件
divs[0].addEventListener('click',function(){
alert('father')
})
// 子div注册绑定事件
divs[1].addEventListener('click',function(){
alert('son')
})
document.addEventListener('click',function(){
alert('document')
})
</script>
</body>
</html>
e.stopPropagation() - ie9及以上可用
event.stopPropagation() 方法阻止事件冒泡到父元素,阻止任何父事件处理程序被执行。
阻止事件冒泡示例及效果图:
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>15-阻止事件冒泡</title>
<style>
.father {
margin: 10px auto;
width: 150px;
height: 150px;
background-color: blueviolet;
position: relative;
cursor:pointer;
}
.son {
width: 80px;
height: 80px;
background-color: pink;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
text-align: center;
line-height: 80px;
cursor:pointer;
}
</style>
</head>
<body>
<div class="father">
<div class="son">son</div>
</div>
<script>
var divs = document.querySelectorAll('div')
// 父div注册绑定事件
divs[0].addEventListener('click',function(){
alert('father')
})
divs[1].addEventListener('click',function(e){
alert('son')
// 阻止冒泡事件 ie 6、7、8不支持
e.stopPropagation()
})
document.addEventListener('click',function(){
alert('document')
})
</script>
</body>
</html>
此为非标准,在ie6、7、8用 e.cancelBubble = true;
在普通浏览器中标准写法是用e.stopPropagation()方法;
在低版本的浏览器我们是用cancelBubble = true;
阻止冒泡事件的兼容性解决方案
代码示例:
if(e && e.stopPropagation){
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}