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

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

    Updated the solution to:

    • use mouseenter and mouseleave instead
    • of hover use live event binding

    var mouseOverActiveElement = false;

    $('.active').live('mouseenter', function(){
        mouseOverActiveElement = true; 
    }).live('mouseleave', function(){ 
        mouseOverActiveElement = false; 
    });
    $("html").click(function(){ 
        if (!mouseOverActiveElement) {
            console.log('clicked outside active element');
        }
    });
    
    0 讨论(0)
  • 2020-11-21 05:04

    Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

        var button = $('#open')[0]
        var el     = $('#test')[0]
    
        $(button).on('click', function(e) {
          $(el).show()
          e.stopPropagation()
        })
    
        $(document).on('click', function(e) {
          if ($(e.target).closest(el).length === 0) {
            $(el).hide()
          }
        })
    
        $(document).on('keydown', function(e) {
          if (e.keyCode === 27) {
            $(el).hide()
          }
        })
    
    0 讨论(0)
  • 2020-11-21 05:04

    According to the docs, .blur() works for more than the <input> tag. For example:

    $('.form_wrapper').blur(function(){
       $(this).hide();
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 05:05
    $(document).click(function(event) {
        if ( !$(event.target).hasClass('form_wrapper')) {
             $(".form_wrapper").hide();
        }
    });
    
    0 讨论(0)
  • 2020-11-21 05:06

    Had the same problem, came up with this easy solution. It's even working recursive:

    $(document).mouseup(function(e) 
    {
        var container = $("YOUR CONTAINER SELECTOR");
    
        // if the target of the click isn't the container nor a descendant of the container
        if (!container.is(e.target) && container.has(e.target).length === 0) 
        {
            container.hide();
        }
    });
    
    0 讨论(0)
提交回复
热议问题