我有这段代码显示了一个显示弹出窗口的按钮,我希望用户能够通过在打开弹出窗口时单击它来关闭弹出窗口。
所以我想将方法“ Close()”分配给事件列表程序,该程序可以检测到类'.popup'的外部单击,现在这只是一个警报。
问题是,当我单击该按钮时,即使弹出窗口尚未打开,它也已经从警报开始,我希望事件列表器在弹出窗口打开后就开始工作,而不是以前。
任何建议删除重复代码也将受到赞赏。
谢谢。
/* Clean up the URL from '#popup1' in the end */
history.replaceState(null, null, ' ');
/* Take off the popup from DOM before clicking in case user refresh*/
let id_popup = document.querySelector('#popup1');
let popup = id_popup.parentNode
popup.removeChild(id_popup);
/*Opening the popup*/
function Open() {
popup.appendChild(id_popup);
let class_popup = document.querySelector('.popup');
window.addEventListener('click', function (e) {
if (!class_popup.contains(e.target)) {
alert('You\'re clicking outside the popup !')
}
});
}
/*Closing the popup*/
function Close() {
popup.removeChild(id_popup);
history.replaceState(null, null, ' ');
}
.button {
font-size: 1em;
padding: 10px;
color: #000;
border: 2px solid #06D85F;
border-radius: 20px/50px;
text-decoration: none;
cursor: pointer;
transition: all 0.3s ease-out;
}
.button:hover {
background: #06D85F;
}
.overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
transition: opacity 500ms;
visibility: hidden;
opacity: 0;
}
.overlay:target {
visibility: visible;
opacity: 1;
}
.popup {
margin: 70px auto;
padding: 20px;
background: #fff;
border-radius: 5px;
width: 60%;
position: relative;
transition: all 5s ease-in-out;
}
.popup h2 {
margin-top: 0;
color: #333;
font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.popup .close:hover {
color: #06D85F;
}
.popup .content {
max-height: 30%;
overflow: auto;
}
@media screen and (max-width: 700px) {
.box {
width: 70%;
}
.popup {
width: 70%;
}
}
<a class="button" href="#popup1" onclick="Open()">Let me Pop up</a>
</div>
<title>hi</title>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Title</h2>
<a class="close" onclick="Close()" href="javascript://">×</a>
<div class="content">
Text
</div>
</div>
答案 0 :(得分:1)
尝试以下操作:
let allElems = document.querySelectorAll("body > div:not(#popup1)"); // Special query selector to get everything except .popup and its children
Array.from(allElems).forEach(elem => // Convert to iterable (with Array.from) and loop through all elements selected
elem.addEventListener('click', function (e) { // Give them all the click event listener.
alert('You\'re clicking outside the popup !')
});
}
问题主要出在您的if
语句上,因为.contains
有点混乱。另一种选择是将两个元素都转换为字符串并以这种方式进行比较,但是这种方法更好,也更快(略),因为我们不需要检查每个单击是否在框中。 / p>