Use jQuery to hide a DIV when the user clicks outside of it

后端 未结 30 3504
庸人自扰
庸人自扰 2020-11-21 04:28

I am using this code:

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

$(\'.form_wrapper\').click(function(event){
   event.stopPropagatio         


        
30条回答
  •  花落未央
    2020-11-21 05:14

    (Just adding on to prc322's answer.)

    In my case I'm using this code to hide a navigation menu that appears when the user clicks an appropriate tab. I found it was useful to add an extra condition, that the target of the click outside the container is not a link.

    $(document).mouseup(function (e)
    {
        var container = $("YOUR CONTAINER SELECTOR");
    
        if (!$("a").is(e.target) // if the target of the click isn't a link ...
            && !container.is(e.target) // ... or the container ...
            && container.has(e.target).length === 0) // ... or a descendant of the container
        {
            container.hide();
        }
    });
    

    This is because some of the links on my site add new content to the page. If this new content is added at the same time that the navigation menu disappears it might be disorientating for the user.

提交回复
热议问题