单击任何地方但菜单时,jQuery隐藏下拉列表 [英] jQuery hide dropdown when clicked anywhere but menu

查看:124
本文介绍了单击任何地方但菜单时,jQuery隐藏下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将其设置为当您单击按钮时显示我的下拉菜单,并且当您单击除下拉菜单之外的任何位置时隐藏该隐藏菜单。

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


推荐答案

这是我决定使用的,它是一个很好的小jQuery插件,可以使用很少的代码。

This is what I've decided to use, it's a nice little jQuery plugin that works with little code.

这是插件:
http://benalman.com/projects/jquery-outside-events-plugin/

这是在我的问题中使我的上述代码工作的代码。

This is the code that makes my above code in my question work.

$(document).ready(function(){
    $(".notification-button").click(function(){
        $('.notification-container').toggle().animate({"margin-top":"0px"}, 75); 
    }); 

    $('.notification-wrapper').bind('clickoutside', function (event) {
        $('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
    });
});

这篇关于单击任何地方但菜单时,jQuery隐藏下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆