事件冒泡和事件捕获
一、事件冒泡原理及举例图解
事件冒泡:所谓冒泡指的就是事件的向上传导,当后代元素上的事件被触发时,其祖先元素的相同事件也会被触发,可以理解为一条鱼在水中吐泡,而这个泡是从水里向水面传送,里到外。
😄看一个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>事件冒泡</title>
</head>
<body>
<div onclick="fun()"></div>
</body>
</html>
你看我点一下里面的div,它就会一个冒泡事件,但是这个冒泡事件我们是看不到的,但是它是按这个顺序发生的:
1.<div>
2.<body>
3.<html>
4.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>Document</title>
</head>
<style>
div{
width: 100px;
height: 50px;
border: 1px solid red;
background-color: brown;
color: black;
line-height: 50px;
text-align: center;
}
</style>
<body>
<div>点击</div>
<script>
var body=document.getElementsByTagName('body')[0];
window.addEventListener('click',function(){
console.log('window')
},false)//默认第三个参数是false,表示该事件是冒泡事件
body.addEventListener('click',function(){
console.log('body')
},false)
var oDiv=document.getElementsByTagName('div')[0];
oDiv.addEventListener('click',function(){
console.log(1)
},false)
oDiv.addEventListener('click',function(){
console.log(2)
},false)
</script>
</body>
</html>
点击div之后控制台输出如下:
二、事件捕获原理及举例图解
事件捕获:事件捕获实际上是为了在事件到达最终目标 前拦截事件,顾名思义就是捕获某个东西。
😄看这个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>事件捕获</title>
</head>
<body>
<div onclick="fun()"></div>
</body>
</html>
同样的图,但是它们的触发顺序却不同,如下:
1、 document
2、<html>
3、<body>
4、<div>
可以看出它是从最外面开始触发的,直到捕获到你点击的div为止,模型图如下:
☀️事件捕获例子:
<!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>Document</title>
</head>
<style>
div{
width: 100px;
height: 50px;
border: 1px solid red;
background-color: brown;
color: black;
line-height: 50px;
text-align: center;
}
</style>
<body>
<div>点击</div>
<script>
var body=document.getElementsByTagName('body')[0];
window.addEventListener('click',function(){
console.log('window')
},true)//第三个参数为true,表示该事件是捕获事件
body.addEventListener('click',function(){
console.log('body')
},true)
var oDiv=document.getElementsByTagName('div')[0];
oDiv.addEventListener('click',function(){
console.log(1)
},true)
oDiv.addEventListener('click',function(){
console.log(2)
},true)
</script>
</body>
</html>
点击div之后控制台输出如下:
三、二者区别
事件冒泡:一个由里到外,冒泡,向上层延申。
事件捕获:一个由外到里,前往捕获,形成向下趋势。
图解如下: