點擊彈窗可以正常跳出,但是黑背景只有點擊最後一個元素會顯示,想請問怎麼修改比較好~
<div id="dark-bg" class="dark-bg-display"></div>
<div class="popup-target">
<div class="ov2-1">1</div>
<div class="ov2-2">2</div>
<div class="ov2-3">3</div>
<div class="ov2-4">4</div>
<div class="ov2-5">5</div>
<div class="ov2-6">6</div>
<div class="ov2-7">7</div>
</div>
<div class="popup-items">
<div class="proto-1 proto-display">
<div class="proto-2 proto-display">
<div class="proto-3 proto-display">
<div class="proto-4 proto-display">
<div class="proto-5 proto-display">
<div class="proto-6 proto-display">
<div class="proto-7 proto-display">
</div>
const ov_all = function (){
document.addEventListener('click',(e)=>{
for(let i = 1 ; i < 8 ; i++){
let proto_all = document.querySelector(`.proto-${i}`)
let ov_all = document.querySelector(`.ov2-${i}`)
let dark_bg = document.getElementById('dark-bg')
dark_bg.style.height =document.documentElement.scrollHeight+`px`
dark_bg.style.width = document.documentElement.scrollWidth+`px`;
if(e.target == ov_all){
proto_all.classList.remove('proto-display')
dark_bg.classList.remove('dark-bg-display')
}
else if(e.target !== ov_all){
proto_all.classList.add('proto-display')
dark_bg.classList.add('dark-bg-display')
}
}
})
}()
我看錯了所以更新回答
不管點擊哪一個都會去跑 for 迴圈
所以當你點擊 <div class="ov2-1">1</div>
跑完 for 迴圈依然會被 <div class="ov2-7">7</div>
不等於 e.target 影響加上 dark-bg-display
所以只要加上 break 就好
if (e.target == ov_all) {
proto_all.classList.remove('proto-display');
dark_bg.classList.remove('dark-bg-display');
break;
} else if (e.target !== ov_all) {
proto_all.classList.add('proto-display');
dark_bg.classList.add('dark-bg-display');
}