非ie 浏览器的方法:
e.stopPropagation()
ie浏览器的方法:
cancelBubble()
案例演示
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<style>
.parent {
width: 200px;
height: 200px;
background: green;
}
.child {
width: 100px;
height: 100px;
background: hotpink;
}
</style>
<div id='parent' class="parent">
<div id='child' class="child"></div>
</div>
<script>
//因为事件冒泡是默认存在的,所以子元素发生的变化,同时会传递给父元素
parent.onclick = function() {
console.log('parent被触发了'); //当点击在父元素的div中时的时候,会打印parent被触发了
}
child.onclick = function(e) {
console.log('child被触发了'); //当点击子元素的div时,会打印child被触发了,parent被触发了
// //阻止冒泡
e.stopPropagation(); //但是没有这行代码的时候,只会打印child被触发了,此时冒泡被阻止了
// //IE浏览器
// //cancelBubble()
}
</script>