温馨提示:本文翻译自stackoverflow.com,查看原文请点击:html - Use jQuery to hide a DIV when the user clicks outside of it
html jquery hide styling

html - 当用户在DIV外边点击时,如何使用jQuery隐藏该DIV呢?

发布于 2020-03-31 23:18:08

我正在使用此代码:

$('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 - Front-End UX
被浏览
13
user659025 2017-05-13 16:29

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

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