Hide menu onClick

2019-07-07 04:48发布

I have this dropdown menu, that will slideDown whenever my users click on a link. However, I don't know how to make it slideUp, whenever the user click somewhere on the page (Not on the menu of course).

My CSS looks like this:

<li class="da-header-button message">
    <span class="da-button-count">32</span>
    <a href="#">Notifications</a>
    <ul class="subnav">
        <li class="head"><span class="bold">Notificatons</span></li>
        <li class="item"><a href="#">Under menu</a></li>
        <li class="item"><a href="#">Under menu</a></li>
    </ul>
</li>

My current jQuery code looks like this:

jQuery("ul.topnav li").click(function() { //When trigger is clicked...  
    //Following events are applied to the subnav itself (moving subnav up and down)  
    jQuery(this).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  
    jQuery(this).hover(function() {  
    }, function(){  
        jQuery(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
    });  
});

If I edit the last jQuery function from this: jQuery(this).hover(function() to this: jQuery(this).click(function() it does not work, since it will just slideDown and then up right after.

Thank you for your help.

EDIT:

Thanks guys! But what if I have two of these submenus open at the same time? How can I prevent this?

I only want to allow to have 1 open.

3条回答
男人必须洒脱
2楼-- · 2019-07-07 05:01

Slide up all visible menus when a click propagates to the document:

$(document).on("click", function(){
    $(".subnav:visible").slideUp();
});

Then prevent this from happening when you're within menus by stopping the event propagation.

$("ul.topnav").on("click", "li", function(e){
    e.stopPropagation();
    $(".subnav:visible", $(this).siblings()).slideUp("fast");
    $(".subnav", this).slideDown();
});

Fiddle: http://jsfiddle.net/jonathansampson/qQsdN/

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-07 05:19

This JQuery should work:

$('#nav li').hover(
    function () {
        //show its submenu
        $('ul', this).slideDown(100);

    },
    function () {
        //hide its submenu
        $('ul', this).slideUp(100);        
    }
);
查看更多
对你真心纯属浪费
4楼-- · 2019-07-07 05:20

jQuery(this).find() will find descendents of "this." In your code, "this" has changed because of the new closure "function()."

Try this:

jQuery("ul.topnav li").click(function() { //When trigger is clicked...  

    var me = this;
    //Following events are applied to the subnav itself (moving subnav up and down)  
    jQuery(me).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  

    jQuery(me).click(function() {  
    }, function(){  
        jQuery(me).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
    });  

});
查看更多
登录 后发表回答