点击该元素后,我的 dom 中有一个按钮,另一个元素将显示,我想通过使用 vanilla js 单击窗口对象来隐藏该元素 这是我的显示元素代码
const button = document.querySelector('.button');
const box = document.querySelector('.box');
button.addEventListener('click',(e)=>{
e.target.style.display = "none";
box.style.display = "block";
})
这是我隐藏框的代码
window.addEventListener('click',(e)=>{
e.target.style.display = "block";
box.style.display = "none";
})
最佳答案
我想这就是你需要的,请参阅评论
const box = document.querySelector('.box');
const myButton = document.querySelector(".button");
myButton.addEventListener('click',(e)=>{
e.stopPropagation(); // You need to stop propagation, if not the event will bubble to the window and fire the click event of window
e.target.style.display = "none"; // Hise the button
box.style.display = "block"; // Show the box
})
window.addEventListener('click',(e)=>{
box.style.display = "none"; // Hide the box
myButton.style.display = "block"; // Show the button
})
.box {
display:none;
}
<div class="box">This is the box</div>
<button class="button">Button</button>
关于javascript - 使用 vanilla js 在 Dom 上显示元素后,通过单击窗口对象来隐藏元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52518701/