javascript - 通过单击关闭 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>
解决方案
只需在文档上添加另一个侦听器,它将关闭所有打开的模式。
然后在您的模式上添加/修改一个,这将阻止点击事件冒泡。
最终结果是,点击任意位置,如果点击在模态框上方,模态框将拦截并阻止,否则单击其他任何位置,然后文档将收到冒泡事件并关闭模态框...
为了更好地衡量,您可以为esc
keydown 事件添加侦听器并关闭任何打开的模式
推荐阅读
- r - 我怎样才能把情节条形图放在顶层
- mysql - 日志文件中的目标插入行数与数据库中的实际插入不同的可能原因是什么?
- ansible - 当条件总是评估为假时 Ansible
- c++ - 如何在没有循环的情况下用-1初始化整个数组
- java - 如何在Java中删除字符串中的第一个和最后一个字符?
- javascript - 使用 Laravel 提交带有文本字段值和图像的 AJAX 请求
- python - 无法加载 sklearn.datasets 导入 load_iris
- android - 列表重复从一个片段导航并在 NavigationComponents 中返回
- apache-spark - 并行运行多个 Spark 应用程序
- python - 我发现在 python 中为 numpy 数组编制索引很奇怪