简体   繁体   English

jQuery-防止点击事件通过上层触发

[英]Jquery - Prevent click event from being triggered through an overlying layer

.PopBgd is 100% of the screens size with another div .PopUp contained within .PopBgd and appearing on top of it. .PopBgd是屏幕大小的100%,另一个div .PopUp包含在.PopBgd中,并显示在屏幕顶部。 Clicking on .PopBgd gives the desired effect of Hiding. 单击.PopBgd可获得所需的隐藏效果。 However clicking anywhere in PopUp also runs the fadeOut part of the script below. 但是,单击PopUp中的任何位置也会运行下面脚本的fadeOut部分。

QUESTION How to prevent the fadeOut part of the script from triggering though overlying divs? 问题如何防止脚本的fadeOut部分通过上覆的div触发?

$('.BtnPop').click(function(e) {
    e.preventDefault();
    $($(this).data('popup')).fadeIn();
    $('.PopClose, .PopBgd').click(function() {
    $('.PopBgd').fadeOut();});
});

ANSWER 回答

<button type="button" class="BtnPop" data-popup=".Pop1">CLICK</button>

<div class="Pop1 PopBgd">
  <div class="PopUp">
    <a class="PopClose">&#215;</a>
    <div>Content</div>
  </div>
</div>

$('.BtnPop').click(function(e) {
    e.preventDefault();
    $($(this).data('popup')).fadeIn();
});
$('.PopClose, .PopBgd').click(function() {
$('.PopBgd').fadeOut();});

$('.PopUp').click(function(e) {
    e.stopPropagation();
});

NEW QUESTION How to use StopPropogation when the target div's name is unknown? 新问题当目标div的名称未知时,如何使用StopPropogation? What I have tried above does not work. 我上面尝试过的方法不起作用。

I resolved my additional problem by simply adding a second class name that was static to the desired div to allow stopPropogation to work as normal. 我通过简单地将一个静态的第二个类名添加到所需的div来允许stopPropogation正常工作,解决了我的其他问题。

$('.Pop').click(function(e) {
    e.stopPropagation();
});

.stopPropagation() "Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event." “ .stopPropagation()防止事件冒泡DOM树,从而防止任何父处理程序收到该事件的通知。

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

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