小编典典

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

html

我正在使用此代码:

$('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单击时它们不再起作用。


阅读 340

收藏
2020-05-10

共1个答案

小编典典

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

$(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();
    }
});
2020-05-10