<!DOCTYPE html>
<html lang="zh">
<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></title>
<style>
#big{
width: 200px;
height: 200px;
background-color: red;
}
#small{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div id="big">
<div id="small"></div>
</div>
<div></div>
<script>
var big = document.getElementById("big")
var small = document.getElementById("small")
// big.onclick = function(e){
// console.log("红色div")
// }
//
// small.onclick = function(e){
// console.log("蓝色div")
// e.stopPropagation()
// }
// 事件传递分为两个阶段:挖洞(捕获)阶段,冒泡阶段
// 先从上层到下层进行捕获阶段,然后从下层到上层进行冒泡过程
// 通过标签属性绑定的事件和元素标签对象属性绑定事件,都是冒泡阶段触发
// 通过添加事件监听绑定事件
// 1.事件类型 2.事件函数 3.布尔值,表示是否在捕获阶段触发, 默认false,表示不在捕获阶段触发
big.addEventListener("click", function(e){
console.log("红色、捕获阶段触发")
// stopProgration 阻止事件继续传播
// e.stopPropagation()
}, true)
big.addEventListener("click", function(){
console.log("红色、冒泡阶段触发")
}, false)
small.addEventListener("click", function(){
console.log("蓝色、捕获阶段触发")
}, true)
small.addEventListener("click", function(e){
console.log("蓝色、冒泡阶段触发")
// e.stopPropagation()
}, false)
</script>
</body>
</html>
js事件传播
最新推荐文章于 2024-06-18 19:06:56 发布