【问题标题】:Click on overlapping div using pointer-events and hide div使用指针事件单击重叠 div 并隐藏 div
【发布时间】:2016-08-15 01:01:15
【问题描述】:

我编写了这段代码,以便在单击“内部 div”后,使用“pointer-events: none;”单击转到“外部 div”。在 CSS 中。

$("#outer").click(function(){
alert("outer clicked")

});

$("#inner").click(function(e){
    alert("inner clicked")
    this.style.display = 'none'; 
    e.stopPropagation();
});
#outer {
    width:300px;
     height:200px;
     border:3px solid;
     margin:auto;
     background: green;

}
#inner {
  pointer-events: none;
  position: absolute; 
  top: 150px; 
  left: 120px;
  width: 100px;
  height: 100px;
  background: yellow;
  border:3px solid;
  margin:auto;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
    <div id="inner">inner div</div>
     Outer div
</div>

OK,功能完善。但是,如果您单击外部 div 中的任何位置,我需要隐藏内部 div。我尝试使用this.style.display = 'none';,但它不起作用。

【问题讨论】:

  • 对 DOM 中的当前选定元素使用 $(this)。 $(this).css("display","none");应该做的伎俩。

标签: javascript jquery html css


【解决方案1】:

您只需要在#outer 上设置一个事件侦听器,即可在点击#outer 时隐藏内部div。

$('#outer').click(function (e) {
    $('#inner').hide();
});
#outer {
    width:300px;
     height:200px;
     border:3px solid;
     margin:auto;
     background: green;

}
#inner {
  pointer-events: none;
  position: absolute; 
  top: 150px; 
  left: 120px;
  width: 100px;
  height: 100px;
  background: yellow;
  border:3px solid;
  margin:auto;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
    <div id="inner">inner div</div>
     Outer div
</div>

【讨论】:

    【解决方案2】:

    $("#outer").click(function(){
    alert("outer clicked")
    
    });
    
    $("#inner").click(function(e){
        alert("inner clicked")
        this.style.display = 'none'; 
        e.stopPropagation();
    });
    #outer {
     width:300px;
     height:200px;
     border:3px solid;
     margin:auto;
     background: green;
     position:relative;
    
    }
    #inner {
      position: absolute; 
      top: 150px; 
      left: 120px;
      width: 100px;
      height: 100px;
      background: yellow;
      border:3px solid;
      margin:auto;
      z-index:10;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="outer">
        <div id="inner">inner div</div>
         Outer div
    </div>

    在您的示例中,pointer-events 的使用是允许单击或点击行为“通过”一个元素到另一个元素。

    【讨论】:

    • @isabela 事实上,我不明白你为什么需要“pointer-events:none;”。这是您需要的其他东西吗?
    • 指针事件它的点击是下面的div...当点击''内部''时,他会转到“外部”。明白吗?对不起我的英语:(
    猜你喜欢
    • 2014-06-09
    • 1970-01-01
    • 2021-06-14
    • 2015-10-15
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多