JS事件流
事件流:简单来说就是事件的传递机制
事件流分为两种:
1.冒泡:事件由具体的触发元素层层向外传递,直到最外层当代浏览器的主流机制
2.捕获:事件由最外层向内层层传递,直到具体触发者
实例加解决方法:
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
.one{width: 200px;height: 200px;background: red;}
.two{width: 100px;height: 100px;background: green;}
</style>
</head>
<body>
<div class="one">
<div class="two"></div>
</div>
<script>
var o1=document.getElementsByClassName('one')[0];
var o2=document.querySelector('.two');
document.body.onclick=function(e){
console.log(e);
alert('body');
};
o1.onclick=function(){
alert('div1');
};
o2.onclick=function(e){
alert('div2');
//拦截冒泡
// e.stopPropagation(); // IE低版本上不能使用 方法1
// e.cancelBubble=true; 放法2
e?e.stopPropagation():window.event.cancelBubble=true; //兼容性
};
</script>
</body>
</html>
注意:
一定要注意兼容性的问题。