如何在点击和用户点击离开时关闭菜单? [英] How do I close menu on click and when the user clicks away?

查看:164
本文介绍了如何在点击和用户点击离开时关闭菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

(function ($) {
    $(document).ready(function () {
        $(".clicker_class").click(function () {
            $('.show_menu_users').show();
        });
    });
})(jQuery);

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

我是JQuery的新手,有点困惑。我很容易能够使用show函数,但是我需要使用关闭或隐藏功能来关闭菜单,当用户再次点击.clicker_class和当用户点击离开别的东西。我尝试使用e.stopPropogation();但没有工作。

I am new to JQuery and a bit puzzled. I was easily able to use the show function but I need to use the close or hide function to close the menu when the user clicks on .clicker_class again and when the user clicks away at something else. I tried using the e.stopPropogation(); but didn't work. How do I do that given my above code?

更新:

I got it to close if a user clicks elsewhere using this:

$(document).mouseup(function (e)
{
    var container = $(".clicker_class");

    if (container.has(e.target).length === 0)
    {
         $(".show_menu_users").hide();
    }
});

问题:

现在我只需要在用户点击.clicker_class时关闭菜单。

Now I just need the menu to close when the user clicks on .clicker_class. How can i do that now?

推荐答案

UPDATED如果在 clicker_class 元素。

UPDATED to close menu if clicked outside of clicker_class elements.

您可以使用布尔值跟踪 show_menu_users 的状态。当您点击 clicker_class 元素时,切换菜单并更新布尔值。当您点击文档中的其他地方时,关闭菜单。

You can track the state of the show_menu_users using a boolean. When you click on the clicker_class elements, toggle the menu and update the boolean. When you click elsewhere in teh document, close the menu.

(function ($) {
    $(document).ready(function () {
        var isShowing = false;

        var toggleMenu = function() {
            isShowing = !isShowing; //change boolean to reflect state change
            $('.show_menu_users').toggle(isShowing); //show or hide element
        }

        $(document).on('click', function (e) {
            if($(e.target).is('.clicker_class') || $(".clicker_class").has(e.target).length !== 0) {
                toggleMenu();
            } else {
                isShowing = false;
                $('.show_menu_users').hide();  
            }
        });
    });
})(jQuery);

这里的工作示例

这篇关于如何在点击和用户点击离开时关闭菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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