防止底层 div 的 onclick 事件触发

6
我正在尝试创建一个覆盖层,其具有一个外部div(半透明)和上面一个较小的内部内容div。 点击外部区域会使覆盖层消失。 点击内容区域应与覆盖层内容交互。
查看我的示例代码,首先单击红色区域会引发警报“red”,然后是警报“black”,因此在第一次交互后立即关闭覆盖层。
我如何防止下面的黑色div的onclick事件在单击上面的红色div时触发?

    <div onclick = "window.alert('black')" style = "background-color:black; width:100%; height:100%">
     <div  onclick = "window.alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;">
      some content
     </div>
    </div>

除了将 pointer-events 设置为 none 以禁用用户与覆盖内容的交互之外,我在网上找不到其他相关信息。同时设置不同的 z-indeices 也没有效果。

如果您想验证点击事件是否发生,请访问:https://onlinegdb.com/rJbOmB0FV

1个回答

7

您遇到的是JavaScript行为。

冒泡

冒泡原理很简单。

当一个元素上发生事件时,它首先在该元素上运行处理程序,然后在其父级上运行处理程序,然后一直向上运行到其他祖先。

使用event.stopPropagation()

定义和用法

  • stopPropagation()方法阻止调用相同事件的传播。

  • 传播意味着冒泡到父元素或捕获到子元素。

https://www.w3schools.com/jsref/event_stoppropagation.asp

更新

一个简单的函数将更易于处理。

像这样:

const alert = (text) => {
  event.stopPropagation();
  window.alert(text)
}
<div onclick = "alert('black')" style = "background-color:black; width:100%; height:100%">
    <div  onclick = "alert('red')" style = "background-color:red; position: absolute; top:10%; left:10%; width: 80%; height: 80%;">
        some content
    </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接