javascript - 在其外部单击时,多个模态框不会关闭

标签 javascript css

我在这里关注了这个图: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/

相关文章:

html - 将一组 CSS 表格单元格换行到新行

javascript - 如何向 d3.js 饼图或圆环图添加阴影

javascript - 跟踪输入中的更改[type=text]

javascript - 为什么我的播放按钮不起作用?

javascript - HTML 数据效果到 jQuery

javascript - 如何使链接不可点击?

javascript - 用于单个页面上单个音频元素的 jQuery 预加载器

asp.net - css 不在回发时加载

javascript - 将数据保存在构造函数中以供跨多个对象使用

javascript - Promise 等待解决而不返回