<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#out{
width: 500px;
height: 500px;
background: red;
position: relative;
}
#in{
width: 200px;
height: 200px;
background: green;
position: absolute;
}
</style>
</head>
<body>
<div id="out">
<div id="in"></div>
</div>
<script type="text/javascript">
var out = document.getElementById("out");
var i = document.getElementById("in");
out.addEventListener('click',a,true);
i.addEventListener('click',b,false);
function a(){
out.style.backgroundColor = 'black';
} function b(){
i.style.backgroundColor = 'blue';
}
</script>
</body>
</html>在这段代码中为何点击子元素后父元素也会变色呢?在子元素上已经设置了阻止事件捕获啊?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
关于js中的事件问题?-PHP中文网问答-关于js中的事件问题?-PHP中文网问答
围观一下哦,学习一下。
addEventListener的第三个参数不是用来阻止事件捕获的
第三个参数是来控制事件是在捕获阶段或冒泡阶段执行
在你这个demo里面,当点击子元素时,会产生一个点击事件
事件会按照
捕获:window→document→html→body→#out→#in
执行:#in
冒泡:#in→#out→#body→#html→#document→#window
这样的顺序完成生命周期
你给#out的事件第三个参数设置的ture,那么当点击事件捕获到#out时,就会触发#out的点击事件
想要实现你的要求
out.addEventListener('click',a);//让事件在冒泡阶段捕获 i.addEventListener('click',b,false); function a(){ out.style.backgroundColor = 'black'; } function b(e){ i.style.backgroundColor = 'blue'; e.stopPropagation();//阻止子元素的事件冒泡 }