简体   繁体   English

JavaScript - div的顺序,其中顶部不受来自div下面的onclick脚本的影响

[英]JavaScript - Order of div's where the top one is not affected by onclick scripts from below divs

I have three div boxes that stack on top of each other so that one is closer than the background div. 我有三个div盒子堆叠在一起,以便一个比背景div更接近。 However the background div has this event handler: onclick="hideLarge();" 但是后台div有这个事件处理程序:onclick =“hideLarge();”

The issue is that when I click on the div box at the front even though it is blocking the visibility of the background div, it still triggers that onclick function which I do not want it to do. 问题是当我点击前面的div框时,即使它阻挡了背景div的可见性,它仍会触发我不希望它执行的onclick功能。

Is there a way that the front div box can intercept these? 前面的div盒有没有办法拦截这些?

Thank you! 谢谢!

If your DOM structure is like so: 如果您的DOM结构是这样的:

Document
 |- BODY
     |- DIV(#1)
         |- DIV(#2)
         |- DIV(#3)
             |- DIV(#4)
             |- DIV(#5)

Then clicks on #4,#5 will bubble up to #3 and #1 while clicks on #3 and #2 will bubble to #1. 然后点击#4,#5将冒出#3和#1,而#3和#2的点击将冒泡到#1。

If you on the other hand have a stucture like this: 另一方面,如果你有这样的结构:

Document
 |- BODY
     |- DIV(#1)
     |- DIV(#2)
     |- DIV(#3)
     |- DIV(#4)
     |- DIV(#5)

None of the divs will bobble to other then document.body and document. 没有任何div会夸大其他文件.body和文件。

You can use event.stopPropagation() to stop the event from bubbling up. 您可以使用event.stopPropagation()来阻止事件冒泡。 Say we bind a click listener on #5 in example 1: 假设我们在示例1中绑定#5上的单击侦听器:

div5.addEventListener('click', function(event) {
    event.stopPropagation();
}, false);

The event will be stopped before it reaches div #3 and therefore also not reach #1. 该事件将在到达div#3之前停止,因此也不会达到#1。

If you have multiply click event bound on #5 these will not be stopped. 如果您在#5上绑定了多次点击事件,则不会停止这些事件。 If you wish to stop these you should use event.stopImmediatePropagation() 如果你想停止这些,你应该使用event.stopImmediatePropagation()

Note that some versions of IE have a different way of doing this. 请注意,某些版本的IE使用不同的方法。

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

Check whether the clicked div is background div or not like, Here top div is the id of the div of top one 检查点击的div是否是背景div,这里top div是顶部div的id

function hideLarge(evt) {
if(evt.target.id!='top_div'){
//code
}

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

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