当多个元素设置点击关闭后,会产生点击一个元素的关闭按钮把其他元素也关闭了,我们可以利用父节点来点击关闭只关闭自身。
HTML
<div class="box">
我是广告
<div class="box1">X</div>
</div>
<div class="box">
我是广告
<div class="box1">X</div>
</div>
<div class="box">
我是广告
<div class="box1">X</div>
</div>
CSS
.box {
position: relative;
width: 1000px;
height: 200px;
background-color: pink;
margin: 100px auto;
text-align: center;
font-size: 50px;
line-height: 200px;
font-weight: 700;
}
.box1 {
position: absolute;
right: 20px;
top: 10px;
width: 20px;
height: 20px;
background-color: skyblue;
text-align: center;
line-height: 20px;
font-size: 16px;
cursor: pointer;
}
JS
// 1. 获取事件源
const box1 = document.querySelectorAll('.box1')
for(let i = 0;i < box1.length;i++){
// 2. 事件侦听
box1[i].addEventListener('click', function () {
this.parentNode.style.display = 'none'
})
}