JS事件传播流程-学习笔记
一、事件传播三个阶段
1、 捕获阶段
2、 目标阶段
3、 冒泡阶段
<!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>
#grafather{width: 500px;height: 300px;background-color: teal;margin: auto;}
#father{width: 400px;height: 200px;background-color: yellowgreen;margin: auto;}
#me{width: 300px;height: 100px;background-color: tomato;margin: auto;}
#son{width: 200px;height: 50px;background-color: salmon;margin: auto;}
</style>
</head>
<body>
<div id="grafather" ondblclick="grafa()">
grafather
<div id="father">
father
<div id="me">
me
<div id="son">
son
</div>
</div>
</div>
</div>
<script>
// html事件
function grafa() {
console.log("grafather");
}
// DOM 0级事件
var fath=document.getElementById("father");
fath.onclick=function(){
console.log("father");
}
// DOM 2级事件
var me=document.getElementById("me");
me.addEventListener("click",showme,false);
function showme() {
console.log("me");
}
</script>
</body>
</html>
二、事件绑定(事件处理)三种方式
1、 HTML标签
2、 DOM 0级
3、 DOM 2级(事件监听)
三、问题:捕获和冒泡的设定
DOM2级事件绑定,使用addEventListener第三个参数useCapture是可以设置事件是在捕获阶段执行(true)还是在冒泡阶段执行(false),那么,html标签和dom0级事件,是否可以设置?找了半天也没有确定的答案,唯一可以稍微确定的是,前两个事件都在冒泡阶段执行。当点击me时,捕获阶段没有事件,到me后,冒泡开始,从内到外依次执行me-father-grafather。
四、事件传播过程,都传播了什么?
1、 我直观的理解,事件的传播过程,将鼠标点击事件click从外到内传递,当我把grafather的事件改为ondblclick,点击father或me时,grafather没有执行。
2、 参看https://blog.csdn.net/qq_23389687/article/details/80166843,DOM0和DOM2级事件
3、补充,回头看了事件,一个事件发生后,会生成一个事件对象event,对象里包含了各种信息,包括鼠标点击的屏幕X,Y坐标点,事件的动作。有一个属性path,记录了事件的观光旅游路径。所以我想,既然找到了事件的目标元素等所有信息,为什么不直接执行呢?为什么还要绕一大圈,从上到下又从下到上来一回?而且,如果你不想事件传递,只在点击元素执行事件,可以stopPropogation。不知道ie和netscape当年为什么有此争论,我再去看看。
五、让事件在捕获阶段执行
将4个div全部用addEventListener绑定click事件,并设置为捕获阶段执行
点击son时,从grafather开始执行
将grafather和me设置为冒泡,另两个设置为捕获
六、事件委托
<ul onclick="ulclick()">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<span>aaaa</span>
</ul>
<script>
ulclick=()=>{
if (event.target.tagName=='LI') {
console.log(event.target.innerHTML);
}
}
</script>