如何在 Javascript 外部单击时关闭模式

我试图在外部单击时关闭模式。我尝试循环浏览模态,但无法让它们将其显示设置为无。


这是我的 HTML:


<div class="projects">

            <div data-modal="modal1">

                <div>

                      <p>Coffee</p>

                </div>

                <img src="img/coffee.png" alt="">

            </div>

            <div data-modal="modal2">

                <div>

                       <p>Tea</p>

                </div>

                <img src="img/tea.png" alt="">

            </div>

      </div>


<div class="project-card" id="modal1">

            <button class="close">X</button>

        <div class="overlay">

            <img src="img/coffee.png" alt="">

        </div>

</div>

        

<div class="project-card" id="modal2">

            <button class="close">X</button>

        <div class="overlay">

            <img src="img/tea.png" alt="">

        </div>

</div>

这是我打开模式的代码。


const coffeeGrounds = document.querySelectorAll('.projects > div[data-modal^=modal]');

for (var i = 0; i < coffeeGrounds.length; i++) {

    coffeeGrounds[i].addEventListener('click', function () {

        var x = this.getAttribute('data-modal');

        var a = document.getElementById(x);

        a.setAttribute('style','display:block');

       

    });

}


这是我的代码,当在外部单击以关闭模式时:


window.addEventListener('click',function(){

    

   for(var i = 0; i<coffeeGrounds.length; i++){

         var x = coffeeGrounds[i].getAttribute('data-modal');

             var a = document.getElementById(x);

                console.log(a);

                if(a.style.display === 'block'){

                      a.setAttribute('style','display:none');

                 }

             }

        });

在这里将模态显示设置为无。它也阻止显示模式。


请提供任何帮助,我们将不胜感激。

代码笔: https: //codepen.io/zaidik/pen/bGwpzbE


千巷猫影
浏览 83回答 2
2回答

慕侠2389804

当您在模态窗口外部单击时,事件传播数组中不应包含模态窗口换句话说,利用 event.path 属性工作示例(基于提供的小提琴)&nbsp; window.addEventListener('click', function(e) {&nbsp; const allModals = document.querySelectorAll('.project-card');&nbsp; if (!e.path.some(x => x.className && x.className.includes('project-card'))) {&nbsp; &nbsp; allModals.forEach(x => x.style.display = 'none');&nbsp; }}, true)工作小提琴示例: https:&nbsp;//jsfiddle.net/7pzs1042/

撒科打诨

window.addEventListener('click', function(e) {  const allModals = document.querySelectorAll('.project-card');  //e.path is deprecated// use instead e.composedPath() like this:   let paths = e.composedPath()if (!paths.some(x => x.className && x.className.includes('project-card'))) {    allModals.forEach(x => x.style.display = 'none');  }}, true)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript