简体   繁体   English

单击按钮时显示菜单,单击页面或按钮上的任意位置时隐藏菜单

[英]Show menu when i click on button and hide that when i click anywhere on the page or button

I have small dropdown profile menu with logout button etc. I need to show the menu when I click on the button and hide it when i click anywhere on page or on the button as well. 我有带有退出按钮等的下拉菜单配置文件小菜单。单击按钮时需要显示菜单,单击页面或按钮上的任意位置时也需要隐藏菜单。

<div id='menu'>
    <ul>
        <li class='has-sub'> <a class="testbutton" id="userButton" onclick="dropdown()" href="#">
                            <span id="buttonText">User name</span> <span id="triangleDown">&#9662;</span>
                        </a>

            <ul id="submenu">
                <li class='has-sub'><a href='#'><span>Change password</span></a>
                </li>
                <li class='has-sub'><a href='logout.php?action=0'><span>Logout</span></a>
                </li>
            </ul>
        </li>
    </ul>
</div>

I used JavaScript. 我用过JavaScript。 At this time menu is displayed on hidded only when I click on profile button. 此时,仅当我单击配置文件按钮时,菜单才会显示为隐藏。 I also know how to start function using something like document.ready. 我也知道如何使用诸如document.ready之类的功能来启动功能。

My not working code: 我的无效代码:

function dropdown() {
    if ($('#submenu').css('visibility') == 'hidden') {
        $('#submenu').css('visibility', 'visible');
    } else {
        $('#submenu').css('visibility', 'hidden');
    }
};

$(document).click(function (event) {
    if ($('#submenu').css('visibility') == 'visible') {
        $('#submenu').css('visibility', 'hidden');
    }
});

But when I combine this methods it does not works. 但是,当我结合使用此方法时,它将无法正常工作。 So when I clicked on the button to open menu, nothing happened. 因此,当我单击按钮以打开菜单时,什么也没发生。

Sorry for my English :) Thanks for help in advance. 对不起,我的英语:)预先感谢您的帮助。

This has partly to do with something called event propagation. 这部分与事件传播有关。 Put simply, this means that click events will register not only on the clicked element, but also on any parent or ancestor elements of that element. 简而言之,这意味着click事件不仅会在clicked元素上注册,还会在该元素的任何父元素或祖先元素上注册。

So if you click a DIV, the event will also be registered on the BODY, because the DIV is inside the BODY. 因此,如果您单击DIV,该事件也将在BODY上注册,因为DIV在BODY内部。 Put abstractly, if a kitchen is the scene of a crime, then the apartment that houses that kitchen is also the scene of a crime. 简而言之,如果厨房是犯罪现场,那么容纳该厨房的公寓也是犯罪现场。 One is inside the other. 一个在另一个里面。

This is prevented by preventing propagation - in jQuery, by running the stopPropagation() method of the evt object that is automatically passed to your event handler. 这是通过防止传播来防止的-在jQuery中,通过运行自动传递给事件处理程序的evt对象的stopPropagation()方法来stopPropagation()这种情况的发生。

In any case, your situation can be greatly simplified. 无论如何,您的情况都可以大大简化。

var menu = $('#menu'), but = $('#menu_button');
$(document).on('click', '*', function(evt) {
    evt.stopPropagation(); //<-- stop the event propagating to ancestral elements
    if ($(this).is(but))   //<-- on button click, toggle visibility of menu
        menu.toggle();
    else if (!$(this).closest(menu).length) //<-- on click outside, hide menu
        menu.hide();
});

Assumption: I have assumed that the toggler button is targetable via the selector '#menu_button'. 假设:我假设切换按钮可通过选择器'#menu_button'定位。 Update this as required. 根据需要更新。 Also, the code should run inside a DOM-ready handler. 此外,代码应在DOM就绪处理程序中运行。

The code listens for clicks to any element. 该代码侦听对任何元素的点击。 If it's registered on the button, the visible state of the menu is toggled. 如果在按钮上注册,则菜单的可见状态将被切换。 If it's to an element outside of the menu, the menu is hidden. 如果是菜单外的元素,则菜单被隐藏。 (If, in the latter case, the menu is already hidden, this will have no effect.) (在后一种情况下,如果菜单已经隐藏,则将无效。)

Here's a working JS Fiddle that demonstrates the approach. 这是一个工作的JS小提琴 ,演示了该方法。

Try this: 尝试这个:

$(function() {

    $('.test-button').click(function(event) {
        event.stopPropagation();
        $('#submenu').toggle();
    });

    $('body').click(function() {
        var submenu = $('#submenu');
        if(submenu.is(":visible")) {
            submenu.hide();
        }
    })


});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM