简体   繁体   English

将点击事件转发给后面的元素

[英]Forward a click event to the element behind

I have two divs stacked together and one is behind the other.我有两个 div 堆叠在一起,一个在另一个后面。

<div style='position:relative;'>
  <div style='position: absolute; top:0; left:0;'>
    bottom element
  </div>
  <div style='position: absolute; top:0; left:0;'>
      top element
  </div>
</div>

I installed a click listener to both elements.我为这两个元素安装了一个点击监听器。 However, only the top one gets the event.但是,只有排名靠前的人才能获得该事件。 Some other posts suggest that I can use pointer-event:none to give up handling the click event from the top element.其他一些帖子建议我可以使用pointer-event:none放弃处理顶部元素的点击事件。 However, I want to handle the click events in both elements.但是,我想处理两个元素中的点击事件。

https://jsfiddle.net/zhu63v7o/ https://jsfiddle.net/zhu63v7o/

I'd love to see your JavaScript code but never the less, you can use the z-index property with the conditional statement for this.我很想看到您的 JavaScript 代码,但无论如何,您可以将 z-index 属性与条件语句一起使用。 Also note that the container for both divs should be the one receiving the event while the divs are responding to the event另请注意,两个 div 的容器应该是在 div 响应事件时接收事件的容器

//style //风格

 .inner_div{
  width: 100px;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
}

//HTML //HTML

<div style="position: relative; width: 100px; height: 100px" onclick="myChange(document.querySelector('#one'))">
          <div class="inner_div" id="one" style="background: red">div 1</div>
          <div class="inner_div" id="two" style="background: green">div 2</div>
</div>

//Js //Js

function myChange(x){
  if (x.style.zIndex == "1") {
    x.style.zIndex = "-1"
  }else{
    x.style.zIndex = "1"
  }
}

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

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