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

后端 未结 30 3505
庸人自扰
庸人自扰 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 04:57

    So many answers, must be a right of passage to have added one... I didn't see a current (jQuery 3.1.1) answers - so:

    $(function() {
        $('body').on('mouseup', function() {
            $('#your-selector').hide();
        });
    });
    
    0 讨论(0)
  • 2020-11-21 04:59

    if you have trouble with ios, mouseup is not working on apple device.

    does mousedown /mouseup in jquery work for the ipad?

    i use this:

    $(document).bind('touchend', function(e) {
            var container = $("YOURCONTAINER");
    
              if (container.has(e.target).length === 0)
              {
                  container.hide();
              }
          });
    
    0 讨论(0)
  • 2020-11-21 05:00

    Attach a click event to top level elements outside the form wrapper, for example:

    $('#header, #content, #footer').click(function(){
        $('.form_wrapper').hide();
    });
    

    This will also work on touch devices, just make sure you don't include a parent of .form_wrapper in your list of selectors.

    0 讨论(0)
  • 2020-11-21 05:02

    You'd better go with something like this:

    var mouse_is_inside = false;
    
    $(document).ready(function()
    {
        $('.form_content').hover(function(){ 
            mouse_is_inside=true; 
        }, function(){ 
            mouse_is_inside=false; 
        });
    
        $("body").mouseup(function(){ 
            if(! mouse_is_inside) $('.form_wrapper').hide();
        });
    });
    
    0 讨论(0)
  • 2020-11-21 05:02

    And for Touch devices like IPAD and IPHONE we can use following code

    $(document).on('touchstart', function (event) {
    var container = $("YOUR CONTAINER SELECTOR");
    
    if (!container.is(e.target) // if the target of the click isn't the container...
    && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.hide();
        }
    });
    
    0 讨论(0)
  • 2020-11-21 05:03

    This code detects any click event on the page and then hides the #CONTAINER element if and only if the element clicked was neither the #CONTAINER element nor one of its descendants.

    $(document).on('click', function (e) {
        if ($(e.target).closest("#CONTAINER").length === 0) {
            $("#CONTAINER").hide();
        }
    });
    
    0 讨论(0)
提交回复
热议问题