Close a menu with an anywhere click

2019-02-15 02:03发布

问题:

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", function(){
    $(".dropMenuCont").slideUp();
    if ($(this).next().css("display") == "none") {
        $(this).next().slideDown();
    } else {
        $(this).next().slideUp();
    }
});

So, how can I do the menu slideUp when I click in any place of the page?

Like a document click?

I visited others topics, but I don't know why, this is not working. Maybe I'm doing it in a diferent way.

I accept any tips in the menu coding.

Demo: Jsfiddle

回答1:

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/



回答2:

$(".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



回答3:

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();
});


回答4:

Just bind the click to <body>

$('body').click(function() {
  $(".dropMenuCont").slideUp();
});

$('.dropMenuCont').click(function(e){
  e.stopPropagation();
});


回答5:

$('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.