[英]Multiple modals won't close when clicked outside of it
我在这里遵循这个啧啧: https : //www.w3schools.com/howto/howto_css_modals.asp问题是当我创建两个这样的模态时,第一个在我点击它之外时不会关闭。 这是jsfiddle: https ://jsfiddle.net/j1smeu3c/
// Get the modal
var modal1 = document.getElementById('myModal1');
// Get the button that opens the modal
var btn1 = document.getElementById("myBtn1");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn1.onclick = function() {
modal1.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal1.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
}
//////////////////////////
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the button that opens the modal
var btn2 = document.getElementById("myBtn2");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[1];
// When the user clicks the button, open the modal
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
你的第二个window.onclick
声明会覆盖第一个声明。 您应该在一个函数中设置两个检查。
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
if (event.target == modal1) {
modal1.style.display = "none";
}
}
你有两个window.onclick函数。 删除其中一个并制作如下:
window.onclick = function(event) {
if (event.target == modal1) {
modal1.style.display = "none";
}
if (event.target == modal2) {
modal2.style.display = "none";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.