gpt4 book ai didi

javascript - 如果在弹出窗口外单击,则关闭弹出窗口

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:29 25 4
gpt4 key购买 nike

我有这段代码显示了一个显示弹出窗口的按钮,我希望用户能够在弹出窗口打开时通过点击它的外部来关闭它。

所以我想将方法​​“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://">&times;</a>
<div class="content">
Text

</div>
</div>

最佳答案

尝试以下操作:

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 有点把事情搞砸了。另一种方法是将两个元素都转换为字符串并以这种方式进行比较,但这种方法更好,也更快(稍微),因为我们不需要检查每次点击是否在框中。

关于javascript - 如果在弹出窗口外单击,则关闭弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57445338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com