【问题标题】:Close popup by clicking off JS通过单击关闭 JS 关闭弹出窗口
【发布时间】:2020-07-09 19:48:48
【问题描述】:

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

我已经使用 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>

【问题讨论】:

  • 您还有什么需要澄清的吗?

标签: javascript popup


【解决方案1】:

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

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

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

您可以为esc keydown 事件添加一个监听器并关闭任何打开的模式

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多