【问题标题】:Prevent jquery click function if div clicked within div如果在 div 中单击 div,则防止 jquery 单击功能
【发布时间】:2013-01-14 02:12:03
【问题描述】:

我在自己的背景下使用 twitters bootstrap 模态,因此模态的行为类似于 Pinterest 模态(body-noscroll 和滚动条匹配模态高度)。

我关闭模式的代码是:

$(".modal-container").click(function(e) {
    $('.modal-container .modal').modal('hide');
});
$('.modal').live('hidden', function () {
    $('body').removeClass('noscroll');
    $('.modal-container').hide();
});

但是,当用户在.modal 内部单击时,此功能仍然运行,这是我不想要的。有人可以帮忙吗?

谢谢。

所以html是:

<div class="modal-container">
    <div class="modal">
        Content
    </div>
</div>

CSS 是:

.modal-container {
    overflow-y: scroll;
    position: fixed;
    top: 0;
    right: 0;
    height: 100%;
    width: 100%;
}
.modal {
    position: absolute;
    margin-bottom: 150px;
    width: 630px;
    margin-left: -315px;
    border: 1px solid #e7e7e7;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0;
    z-index: 1052;
    cursor: default;
}

【问题讨论】:

  • 这样做的目的是什么:$('.modal').live('hidden',...); ?
  • 为了简单起见,我省略了其他一些正在运行的代码。这在 twitter 代码关闭模式时运行
  • @adeneo 哦,是的,这是一个我总是忘记的简单解决方案。 :P
  • @adeneo 我应该把代码放在哪里?

标签: jquery html css twitter-bootstrap


【解决方案1】:

编辑了我的 e.stopPropagation 答案,因为它不适用于 OP 请求的事件委托

正如@Adeneo 所评论的,通常更简单的解决方案是检查event target,即发起点击事件的元素是否与您附加点击处理程序的元素相对应:

$(".modal-container").click(function(e) {
    if (e.target === this) $('.modal-container .modal').modal('hide');
});

【讨论】:

  • 我可以在“实时”上下文中使用它吗?加载后,我使用无限滚动在页面上加载更多模式。
  • @bluedaniel 是的,使用委托与 on: $(".modal-container").on('click','.modal',function(e) { e.stopPropagation(); } );
  • 是的,你可以。它也应该可以正常运行。
  • 哦,是的,我只是提醒您不能从委托处理程序调用 e.stopPropagation,我的错。
  • if (e.target === this) 完美运行。感谢您抽出时间不仅帮助我解决这个问题,而且还以一种有助于我前进的方式来解释它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 2018-01-23
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多