开发者

Close a menu with an anywhere click

开发者 https://www.devze.com 2023-03-21 11:55 出处:网络
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.

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?

开发者_JAVA技巧

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


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/


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


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


Just bind the click to <body>

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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消