首页 > 解决方案 > 通过单击关闭 JS 关闭弹出窗口

问题描述

当我单击关闭它/单击另一个弹出窗口时,如何关闭它?

我已经使用 EventListener 来执行第一个弹出窗口的功能,但是当我对第二个弹出窗口执行相同操作时,第一个弹出窗口停止工作。

我尝试使用不同的函数名称和 ID 为弹出窗口复制 JS 代码。

var popup = document.getElementById("myPopup");
  
function myFunction() {
  popup.classList.toggle("show");
}

window.addEventListener('click', ({ target }) => {
  if (!target.closest('.popup') && popup.classList.contains('show')) myFunction();
});

var popup = document.getElementById("myPopup2");
  
function myFunction2() {
  popup.classList.toggle("show");
}

window.addEventListener('click', ({ target }) => {
  if (!target.closest('.popup') && popup.classList.contains('show')) myFunction2();
});
/* Popup container - can be anything you want */
.popup {
  position: relative;
  display: inline-block;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* The actual popup */
.popup .popuptext {
  visibility: hidden;
  width: 160px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 8px 0;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -80px;
}

/* Popup arrow */
.popup .popuptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Toggle this class - hide and show the popup */
.popup .show {
  visibility: visible;
  -webkit-animation: fadeIn 1s;
  animation: fadeIn 1s;
}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
  from {opacity: 0;} 
  to {opacity: 1;}
}

@keyframes fadeIn {
  from {opacity: 0;}
  to {opacity:1 ;}
}
<body style="text-align:center">
<h2>Popup</h2>

<div class="popup" onclick="myFunction()">Click me to toggle the popup!
  <span class="popuptext" id="myPopup">A Simple Popup!</span>
</div>

<h2>Popup2</h2>

<div class="popup" onclick="myFunction2()">Click me to toggle the popup!
  <span class="popuptext" id="myPopup2">A Simple Popup again!</span>
</div>


</body>

标签: javascriptpopup

解决方案


只需在文档上添加另一个侦听器,它将关闭所有打开的模式。

然后在您的模式上添加/修改一个,这将阻止点击事件冒泡。

最终结果是,点击任意位置,如果点击在模态框上方,模态框将拦截并阻止,否则单击其他任何位置,然后文档将收到冒泡事件并关闭模态框...

为了更好地衡量,您可以为esckeydown 事件添加侦听器并关闭任何打开的模式


推荐阅读