繁体   English   中英

如何只单击模态外部而不单击对话框/内容?

[英]How to make click only on modal exterior and not on dialog/content?

因此,我正在和朋友一起扩展Google Chrome浏览器,对于大多数功能(例如日历,设置等),我们都打开了一个模式,因此我们不必重定向到另一个页面。 当您在内容之外单击时,我们试图使模式关闭。 以下是一些标记屏幕截图,可让您大致了解我在说什么。

在此处输入图片说明 我希望能够通过在白色区域之外单击来关闭模式。 目前,即使我在白色区域内单击,它也会关闭。 我已经尝试了几乎所有东西,包括stopPropagation()pointer-events:none; 和jquery禁用。 他们都不是出于我未知的原因而工作。 我猜想关于Chrome扩展程序有些奇怪。 到目前为止,这是我的一些代码:

    function calendar() {
      document.getElementById("calendmodal").style.display = "block";
    }

document.addEventListener("DOMContentLoaded", function () {
  document.getElementById("calendicon").addEventListener("click", calendar);
  document.getElementById("calendmodal").addEventListener("click", closeModal);
  document.getElementById("calendmodal").addEventListener("click", function(event) {
    event.stopPropagation();
  });  
});

和HTML:

<div class="icons" id="icons_calendar">
        <img src='https://preview.ibb.co/jE76Bm/calendar.png' alt="calendar" border="0" id="calendicon"/>
      </div>
    <div id=calendmodal class="generalmodal">
      <div class="modal-content" id="calendcontent">
        <iframe src="https://calendar.google.com/calendar/embed?src=googleapps.wrdsb.ca_ptpdj55efmhg1nb89ruc15fi3k%40group.calendar.google.com&ctz=America%2FToronto" style="border: 0" width="800" height="600" frameborder="0" scrolling="no" visibility="hidden" id="calendiframe"></iframe>
        <p id=infostuff>For a more extensive calendar and<br>more school tools, visit <a href="http://jam.wrdsb.ca">The SJAM Website</a>.</p>
      </div>
    </div>

不太确定自己在做什么错,我不知道该如何扩展。

在您先前的尝试中,您在哪里执行event.stopPropagation() 它不包含在您的代码示例中。

您需要做的是防止#calendmodal上的click事件冒泡DOM并触发其事件处理程序关闭您的模式对话框的body (或另一个容器元素)上的click事件。

您可以这样做:

document.getElementById("calendmodal").addEventListener("click", function(event) {
    event.stopPropagation();
});

我不知道您如何显示模态对话框,但是我针对此问题的方法是这样的(您可以根据具体情况进行调整):

我有一个透明的<div>作为容器,它占据了整个屏幕,并在内部使用CSS放置了模式对话框。 就像是:

<div id="container" style="position:fixed;top:0;bottom:0;left:0;right:0;display:none">
    <div id="myModal" style="position:absolute;width:300px;height:200px;left:100px;top:100px">
        <!-- Here goes my content -->
    </div>
</div>

使用这种方法,要显示对话框,我需要执行以下操作:

function openModal(){
  document.getElementById("container").style.display = "block";
}

并单击透明背景而不是对话框时将其关闭:

document.getElementById("container").onclick = function(event) {
  if (event.target === this) {
    this.style.display = "none";
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM