DOM事件流:捕获阶段、冒泡阶段
捕获阶段- - -事件从顶层节点到底层节点传递:document-》html-》body-》father-》son
冒泡阶段- - -事件从底层节点到顶层节点传递:son-》father-》body-》html-》document
如果各层节点绑定了事件,触发一个元素事件时,会按以上顺序依次执行,即使没动其他事件绑定的对象,一些事件也会执行,就是因为DOM事件流的原因
注意:
onclick 和 attachEvent 只能得到冒泡阶段,
addEventListener() 冒泡 和 捕获阶段 都可以获得
addEventListener()原本有3个参数,最后一个参数不写时,默认是false- - -即冒泡阶段,写了true- - -捕获阶段,写了false- - -冒泡阶段
有些事件是没有冒泡阶段的,如:onblur、onfocus、onmouseenter、onmouseleave
获取不同阶段示例
捕获阶段- - -代码示例:
<!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>DOM事件流</title>
<style>
.father {
width: 300px;
height: 300px;
margin: 100px auto;
padding: 50px;
background-color: green;
box-sizing: border-box;
}
.son {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="father">
father
<div class="son">son</div>
</div>
<script>
var father = document.querySelector('.father');
var son = document.querySelector('.son');
// 捕获阶段,注意son 和 father 都要写 true
son.addEventListener('click', function() {
alert('this is son');
}, true);
father.addEventListener('click', function() {
alert('this is father');
}, true);
</script>
</body>
</html>
页面效果:
没有点击father元素,但是执行了father元素绑定的点击事件,DOM事件流:捕获阶段- - -从顶层节点依次向下层节点检查,直到检查到触发的元素,有绑定事件的就会执行,所以没有点father,也执行了father绑定的点击事件
注意:要获取捕获阶段时,绑定事件的那几个元素都要写true
冒泡阶段- - -代码示例:
<!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>DOM事件流</title>
<style>
.father {
width: 300px;
height: 300px;
margin: 100px auto;
padding: 50px;
background-color: green;
box-sizing: border-box;
}
.son {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="father">
father
<div class="son">son</div>
</div>
<script>
var father = document.querySelector('.father');
var son = document.querySelector('.son');
// 冒泡阶段,不写false也可以,省略默认是false
son.addEventListener('click', function() {
alert('this is son');
}, false);
father.addEventListener('click', function() {
alert('this is father');
}, false);
</script>
</body>
</html>
页面效果:
冒泡阶段- - -从底层向上,依次执行事件