Javascript 打开另一个模式时,如何关闭一个模式?

Javascript 打开另一个模式时,如何关闭一个模式?,javascript,html,css,modal-dialog,Javascript,Html,Css,Modal Dialog,我在我的网站上创建了一些模态。 我想做的是: 当我点击一个模态时,无法点击另一个模态(现在它会打开我点击的所有模态) 我希望在单击另一个模式和要打开的新模式时能够关闭打开的模式 我还希望当我点击页面上的某个地方时,模式关闭 这是我的密码: HTML JAVASCRIPT <script> var modalBtns = [...document.querySelectorAll(".overlay")]; modalBtns.forEach(function(btn)

我在我的网站上创建了一些模态。 我想做的是:

当我点击一个模态时,无法点击另一个模态(现在它会打开我点击的所有模态)

我希望在单击另一个模式和要打开的新模式时能够关闭打开的模式

我还希望当我点击页面上的某个地方时,模式关闭

这是我的密码:

HTML

JAVASCRIPT

<script>
    var modalBtns = [...document.querySelectorAll(".overlay")];
    modalBtns.forEach(function(btn) {
        btn.onclick = function() {
            var modal = btn.getAttribute('data-modal');

            document.getElementById(modal).style.display = "block";
        }
    });

    var closeBtns = [...document.querySelectorAll(".close")];
    closeBtns.forEach(function(btn) {
        btn.onclick = function() {
            var modal = btn.closest('.modal');
            modal.style.display = "none";
        }
    });

    window.onclick = function(event) {
        if (event.target.className === "modal") {
            event.target.style.display = "none";
        }
    }
</script>

var modalBtns=[…document.queryselectoral(“.overlay”)];
modalBtns.forEach(函数(btn){
btn.onclick=函数(){
var modal=btn.getAttribute('data-modal');
document.getElementById(模态).style.display=“块”;
}
});
var closeBtns=[…document.queryselectoral(“.close”)];
closeBtns.forEach(功能(btn){
btn.onclick=函数(){
var modal=btn.最近('.modal');
modal.style.display=“无”;
}
});
window.onclick=函数(事件){
if(event.target.className==“model”){
event.target.style.display=“无”;
}
}

您可以使用css执行此操作:

.modal {
    display:none;
    position:fixed;
    z-index: 1;
    margin:0;
    left:0;
    top:0;
    width:100vw;
    height: 100vh;
    background-color: rgba(0,0,0,0.4);
}
这样,您的模态后面有一个覆盖,它占据了整个视口

这是一支钢笔:


您使用的是哪个引导版本?
<script>
    var modalBtns = [...document.querySelectorAll(".overlay")];
    modalBtns.forEach(function(btn) {
        btn.onclick = function() {
            var modal = btn.getAttribute('data-modal');

            document.getElementById(modal).style.display = "block";
        }
    });

    var closeBtns = [...document.querySelectorAll(".close")];
    closeBtns.forEach(function(btn) {
        btn.onclick = function() {
            var modal = btn.closest('.modal');
            modal.style.display = "none";
        }
    });

    window.onclick = function(event) {
        if (event.target.className === "modal") {
            event.target.style.display = "none";
        }
    }
</script>
.modal {
    display:none;
    position:fixed;
    z-index: 1;
    margin:0;
    left:0;
    top:0;
    width:100vw;
    height: 100vh;
    background-color: rgba(0,0,0,0.4);
}