防止底层div onclick事件触发 [英] Prevent underlying div onclick event to trigger

查看:43
本文介绍了防止底层div onclick事件触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个叠加层,该叠加层具有一个外部div(半透明)并且在一个较小的内部内容div上方.单击外部区域会使叠加层消失.单击内容区域应与覆盖内容进行交互.

I'm trying to create an overlay which has an outer div (half see-through) and above an smaller inner content div. Clicking on the outer area makes the overlay dissappear. Clicking on the content area should interact with the overlay content.

看我的示例代码,单击红色区域会先引发一个警报红色",然后再引发一个警报黑色",因此在第一次交互后立即关闭覆盖.

Looking at my example code, clicking on the red area first raises an alert "red" and afterwards an alert "black" thus closing the overlay immediatly after the first interaction.

当单击上面的红色div时,如何防止底层黑色div的onclick事件触发?

How can I prevent the onclick event of the underlying black div to trigger when the above red div is clicked?

    <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 也不起作用.

I couldn't find anything online about that except people setting pointer-events to none which would disable the user to interact with the overlay content. Also setting different z-indeices didn't work either.

如果您想验证点击是否发生: https://onlinegdb.com/rJbOmB0FV

If you want to verify the clickthrough happening: https://onlinegdb.com/rJbOmB0FV

推荐答案

这更多是您遇到的JavaScript行为.

This is more of a javascript behaviour you're experiencing.

冒泡的原理很简单.

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

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

使用 event.stopPropagation()

定义和用法

  • stopPropagation()方法可防止调用同一事件的传播.

Definition and Usage

  • The stopPropagation() method prevents propagation of the same event from being called.

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

Propagation means bubbling up to parent elements or capturing down to child elements.

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

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

A simple function will be easier to handle.

类似这样的东西:

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>

这篇关于防止底层div onclick事件触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆