为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

千巷猫影 2023-10-14 19:15:51
我试图在外部单击时关闭模式。我尝试循环浏览模态,但无法让它们将其显示设置为无。这是我的 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
查看完整描述

2 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

当您在模态窗口外部单击时,事件传播数组中不应包含模态窗口


换句话说,利用 event.path 属性


工作示例(基于提供的小提琴)


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

  const allModals = document.querySelectorAll('.project-card');

  if (!e.path.some(x => x.className && x.className.includes('project-card'))) {

    allModals.forEach(x => x.style.display = 'none');

  }

}, true)

工作小提琴示例: https: //jsfiddle.net/7pzs1042/


查看完整回答
反对 回复 2023-10-14
?
撒科打诨

TA贡献1934条经验 获得超2个赞

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)


查看完整回答
反对 回复 2023-10-14
  • 2 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信