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

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

    You might want to check the target of the click event that fires for the body instead of relying on stopPropagation.

    Something like:

    $("body").click
    (
      function(e)
      {
        if(e.target.className !== "form_wrapper")
        {
          $(".form_wrapper").hide();
        }
      }
    );
    

    Also, the body element may not include the entire visual space shown in the browser. If you notice that your clicks are not registering, you may need to add the click handler for the HTML element instead.

提交回复
热议问题