Close a menu with an anywhere click

后端 未结 5 1962
无人共我
无人共我 2021-01-06 17:18

As you guys can see, I have a drop down menu.

I have a lot of columns, each one has an option to open the menu.

$(\".optionCont\").live(\"click\", fu         


        
相关标签:
5条回答
  • 2021-01-06 17:41

    Just bind the click to <body>

    $('body').click(function() {
      $(".dropMenuCont").slideUp();
    });
    
    $('.dropMenuCont').click(function(e){
      e.stopPropagation();
    });
    
    0 讨论(0)
  • 2021-01-06 17:50
    $(".optionCont").click(function(e){
        $(".dropMenuCont").slideUp();
        if($(this).next().css("display") == "none"){
            $(this).next().slideDown();
        }else{
            $(this).next().slideUp();
        }
        e.preventDefault();
        e.stopPropagation();
        return false;
    });
    
    $(document).click(function() {
         $(".dropMenuCont").slideUp();
    });
    

    Here is the JSFiddle

    0 讨论(0)
  • 2021-01-06 17:56
    $('body').bind("click",function (){
        $(".dropMenuCont").slideUp();
    });
    $('.dropMenuCont').click(function(event){
        event.stopPropagation();
    });
    

    I think a better idea to check if something is hidden is to toggle the class on your menu in a callback of the animation and then check it with hasClass.

    0 讨论(0)
  • 2021-01-06 17:59

    Try something like:

    $(document).click(function(e) {
       if ($(e.target) != myEl)
           myEl.slideUp();
    })
    

    Alternative: working example.

    Source:

    $(".optionCont").live("click", function(e) {
        var that = this;
        $(document).click(function(e) {
            console.log(e.target);
            console.log(that);
            if (e.target != that) {
                e.stopPropagation();
                e.preventDefault();
                $(".dropMenuCont").slideUp();
            }
        });
        if ($(this).next().css("display") === "none") {
            $(this).next().slideDown();
        } else {
            $(this).next().slideUp();
        }
        e.stopPropagation();
        e.preventDefault();
    });
    
    0 讨论(0)
  • 2021-01-06 18:04

    Register a one-off handler inside the callback to make sure the next click closes the menu:

    $(".optionCont").live("click", function(ev){
        $(".dropMenuCont").slideUp();
        if($(this).next().css("display") == "none"){
            $(this).next().slideDown();
        }else{
            $(this).next().slideUp();
        }
        ev.stopPropagation();
    
        $(document).one('click', function() {
                 $(".dropMenuCont").slideUp();
    
        });
    });
    

    See http://jsfiddle.net/alnitak/GcxMs/

    0 讨论(0)
提交回复
热议问题