<!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>
<body>
<div id="fine">
FINE
</div>
<script>
//冒泡 从下往上
/*
var fine = document.querySelector("#fine")
fine.addEventListener("click",function(){
alert("FINE")
})
var body = document.querySelector("body")
fine.addEventListener("click",function(){
alert("body")
})
var html = document.querySelector("html")
fine.addEventListener("click",function(){
alert("html")
})
document.addEventListener("click",function(){
alert("document")
})
*/
//捕获 从上往下
var fine = document.querySelector("#fine")
fine.addEventListener("click",function(){
alert("FINE")
},true)
var body = document.querySelector("body")
fine.addEventListener("click",function(){
alert("body")
},true)
var html = document.querySelector("html")
fine.addEventListener("click",function(){
alert("html")
},true)
document.addEventListener("click",function(){
alert("document")
},true)
</script>
</body>
</html>
大佬们帮帮忙,冒泡事件正常显示,捕获事件出毛病了,先出现document,第二出现的是FINE,第三是body,第四是html
你怎么全给fine元素绑定事件
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#box {
width: 300px;
height: 300px;
background-color: hotpink;
position: relative;
}
#son {
width: 100px;
height: 100px;
position: absolute;
left: 350px;
top: 350px;
background-color: yellowgreen;
}
</style>
</head>
<body>
<div id="box">
<div id="son"></div>
</div>
</body>
</html>
<script>
1.事件冒泡:从触发事件元素,一级一级往上找父元素触发同名事件,如果有就触发
2.事件捕获:从最顶级的父元素一级一级往下找子元素触发同名事件,直到触发事件的元素为止
* 事件捕获与事件冒泡触发事件的顺序完全相反
3.事件捕获,只能通过addEventListener并且参数写true才是事件捕获
* 其他都是冒泡(不是通过addEventListener添加、addEventListener参数为false)
4.事件对象.stopPropagation() 除了可以阻止冒泡还可以阻止捕获
5.IE8及以前没有捕获!
*/
let box = document.getElementById("box");
let son = document.getElementById("son");
window.addEventListener("click", function () {
alert("这是window");
},true)
document.addEventListener("click", function () {
alert("这是document");
},true)
document.documentElement.addEventListener("click", function (e) {
e = e || window.event;
alert("这是html");
e.stopPropagation();//阻止事件冒泡和事件捕获
},true)
document.body.addEventListener("click", function () {
alert("这是body");
},true)
//参数3:默认是false,代表是支持事件冒泡
box.addEventListener("click", function () {
alert("这是box");
},true)
son.addEventListener("click", function () {
alert("这是son");
},true)
</script>