如何在关闭弹出窗口/单击其他弹出窗口时关闭该弹出窗口?
我已经使用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>
发布于 2020-07-10 03:53:02
只需在文档上添加另一个侦听器,这将关闭所有打开的通道。
然后在你的模式上添加/修改一个,这将阻止点击事件的冒泡。
最终结果是,在任意位置单击,如果单击在模式上,则模式将被拦截并阻止,否则单击其他任何位置,则文档将接收冒泡事件并关闭模式...
另外,您还可以为esc keydown事件添加一个侦听器,并关闭任何打开的通道
https://stackoverflow.com/questions/62822602
复制相似问题