DOM是JS操作网页的接口,全称为“文档对象模型”(Document Object Model)。它的作用是将网页转为一个JS对象,从而可以用脚本进行各种操作(比如增删内容)。
DOM2 Events 规范规定事件流分为 3 个阶段:事件捕获、到达目标和事件冒泡。事件捕获最先发生,为提前拦截事件提供了可能。然后,实际的目标元素接收到事件。最后一个阶段是冒泡,最迟要在这个阶段响应事件
哪一个元素需要阻止冒泡就添加e.stopPropagation()这条语句
有些事件没有冒泡的,如onclur、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>Document</title>
<style>
.father{
width: 200px;
height: 200px;
background-color: aquamarine;
margin: 50px auto;
padding: 10px;
}
.son{
float: left;
width: 100px;
height: 100px;
background-color: chartreuse;
margin-left: 50px;
margin-top: 50px;
}
p{
text-align: center;
padding-top: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"><p>son盒子</p></div>
<div style="clear:both;"></div>
</div>
<script>
// dom事件流三个阶段
// 1.js代码中只能执行捕获或者冒泡其中一个阶段
// 2.onclick和attachEvent只能得到冒泡阶段
// 3.捕获阶段 如果addEventListener 第三个参数true 那么则处于捕获阶段
// document -> html -> body -> father -> son
var son = document.querySelector('.son');
son.addEventListener('click',function(){
alert('son');
},true);
var father = document.querySelector('.father');
father.addEventListener('click',function(){
alert('father');
},true);
// 4.冒泡阶段 如果addEventListener 第三个参数false或者省略 那么则处于冒泡阶段
// son -> father -> body -> html -> document
var son = document.querySelector('.son');
son.addEventListener('click',function(e){
alert('son');
//e.stopPropagation(); //阻止冒泡行为
},false);
//父元素中没有添加阻止冒泡行为,因此当点击父元素区域时document的点击事件还是会执行的
var father = document.querySelector('.father');
father.addEventListener('click',function(){
alert('father');
});
document.addEventListener('click',function(){
alert('document');
})
</script>
</body>
</html>
效果
捕获阶段:
冒泡阶段: