jQuery hide dropdown when clicked anywhere but men

2019-01-21 11:07发布

I'm trying to make it so that my dropdown menu shows when you click a button, and hides when you click anywhere except the dropdown menu.

I have some code working, as far as not closing when you click the menu, however when you click the document when the menu is closed, it shows the menu, so it continuously toggles no matter where you click.

$(document).click(function(event) {
    if ($(event.target).parents().index($('.notification-container')) == -1) {
        if ($('.notification-container').is(":visible")) {
            $('.notification-container').animate({
                "margin-top": "-15px"
            }, 75, function() {
                $(this).fadeOut(75)
            });
        } else {
            //This should only show when you click: ".notification-button" not document
            $('.notification-container').show().animate({
                "margin-top": "0px"
            }, 75);
        }
    }
});

8条回答
Luminary・发光体
2楼-- · 2019-01-21 12:03

This might not be a complete solution but I´ve created a demo to help you out. Let me know it´s not working as you´d expect.

$(document).click(function(e) {

    var isModalBox = (e.target.className == 'modal-box');

    if (!isModalBox) {
        $('.modal-box:visible').animate({
            "margin-top": "-15px"
        }, 75, function() {
            $(this).fadeOut(75);
        });
    }
});

$('a').click(function(e) {
    e.stopPropagation(); // Important if you´d like other links to work as usual.
});

$('#temp-button').click(function(e) {
    e.preventDefault();
    $('.modal-box').show().animate({
        "margin-top": "0px"
    }, 75);
});
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-21 12:08

Try this :

// The code to close the dropdown
$(document).click(function() {
    ...
});

// The code to open the dropdown 
$(".drop-down").click(function() {
    ...
    return false;
});
查看更多
登录 后发表回答