【问题标题】:Clicking content div inside overlay div also closes the popup单击覆盖 div 内的内容 div 也会关闭弹出窗口
【发布时间】:2021-09-21 00:20:33
【问题描述】:

我正在尝试创建一个弹出窗口,其中容器只是具有一些不透明度的黑色背景,然后该 div 容器包含弹出窗口的内容。

基本上它看起来像:

<button (click)="showPopup = !showPopup">Open popup</button>

<div class="overlay-bg" (click)="showPopup = !showPopup" [ngClass]="showPopup ? 'is-active' : ''">
 <div class="content">Some content</div>
</div>

CSS 看起来像这样:

.overlay {
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: grid;
  position: fixed;
  pointer-events: none;
  opacity: 0;

  &.is-active {
    opacity: 1;
    pointer-events: all;
  }

  .content {
    width: 400px;
    height: 400px;
    place-self: center;
    background: red;
  }
}

所以基本上,当状态未激活时,它不会显示,当通过单击按钮启用is-active 时,会显示叠加层+内容。现在,我还想要的是,当单击背景时,弹出窗口应该关闭 - 确实如此。但是,问题是,当我单击内容时,弹出窗口也会关闭——它不应该这样,因为它应该具有一定的交互性。

那么如何防止弹出窗口在与内容 div 交互时关闭?

【问题讨论】:

  • 我不知道(click)="showPopup = !showPopup"这个语法是什么,但是如果你使用纯javascript并添加一个事件处理程序,你会得到event参数。检查event.target 以了解点击事件的来源。 if event.target === &lt;overlay-bg-reference&gt; 然后只执行showPopup = !showPopup
  • 你能在stackblitz中重现问题并在这里分享吗?

标签: html css angularjs


【解决方案1】:

问题

发生这种情况的原因是由于 javascript 中的事件流,即事件处理的顺序。当有嵌套元素时,这一点很重要,比如你的两个 div('overlay-bg' 和 'content')。现代浏览器使用事件冒泡,这意味着最里面的子元素首先处理事件。然后该事件“冒泡”并向外扩展。在您的情况下,“内容”div 必须首先处理事件。您不希望在单击“内容”div 时弹出窗口消失,但在单击“覆盖-bg”div 时会这样做。因此,您必须找到一种方法来阻止事件冒泡的发生,方法是使用“内容”div 上的 onclick 事件捕获它。这可以通过使用事件对象的stopPropagation() 方法来完成。

解决方案

要在用户单击“内容”div 时阻止事件向上冒泡,请在 HTML 中添加 onclick 事件处理程序:

 <div class="content" onclick="preventBubbling(event)">Some content</div>

然后,使用 JavaScript,您可以使用事件对象的 stopPropagation() 方法,该方法作为参数传递给函数。为此,函数如下所示:

function preventBubbling(event) {
    event.stopPropagation();
}

这会阻止事件冒泡到父 div,因此永远不会触发点击事件,并且弹出窗口不会隐藏(当用户点击内容 div 时)。


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多