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

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

    Live demo with ESC functionality

    Works on both Desktop and Mobile

    var notH = 1,
        $pop = $('.form_wrapper').hover(function(){ notH^=1; });
    
    $(document).on('mousedown keydown', function( e ){
      if(notH||e.which==27) $pop.hide();
    });
    

    If for some case you need to be sure that your element is really visible when you do clicks on the document: if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

提交回复
热议问题