webveuje/js/demo/buhuo.html
2021-03-23 10:58:10 +08:00

83 lines
2.6 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!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>
.box{
width: 500px;
height: 500px;
border: 1px solid black;
}
.box1{
width: 300px;
height: 300px;
background: pink;
}
.box2{
width: 100px;
height: 100px;
background: gold;
}
</style>
</head>
<body>
<div class="box">
<div class="box1" >
<div class="box2"></div>
</div>
</div>
<div>
总结点击box2时会接连触发 box() -> box1() -> box2() 整个过程叫做捕获(从外往里)
冒泡和捕获不会同时发生
<p>addEventListener 能给目标元素添加多个事件</p>
<p> 阻止捕获: event.stopImmediatePropagation() event.stopPropagation()</p>
<p>stopImmediatePropagation和stopPropagation 都能阻止捕获但是同一个元素有多个同类型事件的时候stopPropagation不能阻止其他事件的发生
stopImmediatePropagation能阻止其他事件发生的 </p>
</div>
<script>
var boxdj=document.getElementsByClassName('box')[0]
boxdj.addEventListener("click", function (){
console.log("box被点击了")
event.stopImmediatePropagation()
},true)
boxdj.addEventListener("click", function (){
console.log("box被点击了2")
event.stopImmediatePropagation()
},true)
var box1dj=document.getElementsByClassName('box1')[0]
box1dj.addEventListener("click", function (){
console.log("box1被点击了")
event.stopPropagation()
},true)
var box2dj=document.getElementsByClassName('box2')[0]
box2dj.addEventListener("click", function (){
console.log("box2被点击了")
event.stopImmediatePropagation()
},true)
function box(){
console.log("box被点击了")
}
function box1(){
console.log("box1被点击了")
return
}
function box2(){
console.log("box2被点击了")
event.stopImmediatePropagation();
}
function box3(){
console.log("box1被点击了2")
event.stopPropagation();
}
</script>
</body>
</html>