我在这里关注了这个图: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";
}
}
关于javascript - 在其外部单击时,多个模态框不会关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331475/