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

后端 未结 30 4231
庸人自扰
庸人自扰 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:11

    What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked, so your "show" event (or slidedown or whatever shows the dropdown)

        $('.form_wrapper').show(function(){
    
            $(document).bind('click', function (e) {
                var clicked = $(e.target);
                if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                     $('.form_wrapper').hide();
                }
            });
    
        });
    

    Then when hiding it, unbind the click event

    $(document).unbind('click');
    

提交回复
热议问题