gpt4 book ai didi

javascript - 关闭 jQuery 中的模式弹出窗口

转载 作者:行者123 更新时间:2023-11-28 03:06:31 24 4
gpt4 key购买 nike

我有一个图像,单击后将显示模式。如果我在模态窗口外部单击,它会正常关闭,但是如果我单击已放入 span 标记中的 X,它不会关闭。任何帮助将不胜感激!

var modal = document.getElementById("myModal1");
var btn = document.getElementById("myBtn1");
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
<button id="myBtn1" class="button2"><img class="box" src="image.png"></button>
<div id="myModal1" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>Some text in the Modal..</h2>
More text in modal...
</div>
</div>

最佳答案

这是您正在寻找的内容的完整示例

var modal = document.getElementById("myModal1");
var btn = document.getElementById("myBtn1");
var close = document.querySelector("#myModal1 .close");



// When the user clicks anywhere outside of the modal, close it
btn.addEventListener("click",function() {
modal.style.display = "block";
})
close.addEventListener("click",function() {
modal.style.display = "none";
})
window.addEventListener("click",function(e) {
const inside = modal.contains(e.target);
if (!inside && e.target !== btn) {
modal.style.display = "none";
}
})
.modal { display:none }
<button id="myBtn1" class="button2">Click</button>
<div id="myModal1" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<h2>Some text in the Modal..</h2>
More text in modal...
</div>
</div>

关于javascript - 关闭 jQuery 中的模式弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60562353/

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