当用户在 DIV 外部单击时,使用 jQuery 隐藏它

新手上路,请多包涵

我正在使用这段代码:

 $('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

而这个 HTML

 <div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

问题是我在 div 中有链接,单击它们时它们不再起作用。

原文由 Scott Yu - builds stuff 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

有同样的问题,想出了这个简单的解决方案。它甚至可以递归工作:

 $(document).mouseup(function(e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0)
    {
        container.hide();
    }
});

原文由 user659025 发布,翻译遵循 CC BY-SA 3.0 许可协议

你最好选择这样的东西:

 var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){
        mouse_is_inside=true;
    }, function(){
        mouse_is_inside=false;
    });

    $("body").mouseup(function(){
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

原文由 Makram Saleh 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题