Несколько модалов не будут закрываться при нажатии за пределами

1

Я следил за этим вопросом здесь: 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";
    }
}
Теги:

2 ответа

2
Лучший ответ

Второе объявление window.onclick перезаписывает первый. Вы должны установить обе проверки в одной функции.

window.onclick = function(event) {
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
    if (event.target == modal1) {
        modal1.style.display = "none";
    }

}
0

У вас есть две функции window.onclick. Удалите один из них и сделайте следующее:

window.onclick = function(event) {
    if (event.target == modal1) {
        modal1.style.display = "none";
    }
    if (event.target == modal2) {
        modal2.style.display = "none";
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню