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

标签 javascript

点击该元素后,我的 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/

相关文章:

javascript - 将 `__proto__` 用作使用 `Object.create(null)` 创建的对象的属性名称是否安全?

javascript - 在 Bootstrap 中添加后,Rails 表单会 POST 而不是 DELETE 吗?

javascript - Knockout.js 绑定(bind)范围

java - 如何通过 Play Framework 在 JAVA 中使用 HTTP 方法

javascript - toggleclass 不工作?

javascript - 等待异步函数在 map 内部完成

javascript - 加载信息中的指令

javascript - 如何增大或减小整个页面的字体大小

javascript - 如何制作视频填充框?

javascript - 如果我使用JQuery,是否需要使用BluePrint的ie.css?