通过使用香草js在Dom上显示元素后,通过单击窗口对象来隐藏元素?

时间:2018-09-26 13:16:23

标签: javascript

在我的dom中有一个按钮,单击该元素后将显示另一个元素,我想通过使用vanilla js单击window对象来隐藏此元素 这是我的表演元素代码

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";
})

1 个答案:

答案 0 :(得分:2)

我认为这是您所需要的,请参阅评论

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>