首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过单击关闭JS关闭弹出窗口

问通过单击关闭JS关闭弹出窗口
EN

Stack Overflow用户
提问于 2020-07-10 03:48:48
回答 1查看 27关注 0票数 0

如何在关闭弹出窗口/单击其他弹出窗口时关闭该弹出窗口?

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

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

​

代码语言:javascript
复制
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();
});
代码语言:javascript
复制
/* 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 ;}
}
代码语言:javascript
复制
<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>

​

EN

回答 1

Stack Overflow用户

发布于 2020-07-10 03:53:02

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

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

最终结果是,在任意位置单击,如果单击在模式上,则模式将被拦截并阻止,否则单击其他任何位置,则文档将接收冒泡事件并关闭模式...

另外,您还可以为esc keydown事件添加一个侦听器,并关闭任何打开的通道

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62822602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档