3

Here is the jquery code I am using to show and hide my menus.

jQuery(window).load(function () {
    $("#nav > li > a").click(function () { // binding onclick
        if ($(this).parent().hasClass('selected')) {
            $("#nav .selected div div").hide(); // hiding popups
            $("#nav .selected").removeClass("selected");
        } else {
            $("#nav .selected div div").hide(); // hiding popups
            $("#nav .selected").removeClass("selected");
            if ($(this).next(".subs").length) {
                $(this).parent().addClass("selected"); // display popup
                $(this).next(".subs").find("*").slideDown(200);
            }
        }
    });
});

Currently, to hide the drop downs the viewer must click back on the menu heading. I would like to add the function where if they click anywhere else on the page then the menu will hide.

I have read the usual answers but am having trouble integrating them AND properly removing the "selected" class.

I've put everything in jsFiddle here, but unfortunately the code doesn't work on jsFiddle (menus don't drop down). It does, however, work on my live pages when I upload them. Anyone answers as to why that might be would also be helpful and probably get a final solution faster.

4

1 回答 1

1

这应该有你需要的一切:http: //jsfiddle.net/PysAY/5/

除了让小提琴工作之外,我做了很少的改变。

首先,我创建了一个新函数,封装了单击选定菜单时您正在执行的操作。由于您希望在完全单击菜单时出现相同的功能,因此它应该是它自己的功能。

var closeMenu = function() {
    $("#nav .selected div div").hide(); // hiding popups
    $("#nav .selected").removeClass("selected");
};

然后我更改了菜单的click处理程序以调用该函数:

$("#nav > li > a").click(function (e) { // binding onclick
    if ($(this).parent().hasClass('selected')) {
        closeMenu();
    } else {
        // ...
        e.stopPropagation()

我在单击处理程序的顶部和底部添加了行以停止事件传播。这样,下面的正文单击事件将不会收到打开菜单并立即关闭它的单击。

最后,我在正文中添加了一个点击处理程序:

$("body").click(function () {
    closeMenu();
});

只要收到点击,它就会简单地调用 closeMenu 函数。如上所述,我们对其他点击事件执行 stopPropagation 以确保仅在没有其他操作时才发生这种情况。(在小提琴中,你的整个身体都是菜单栏,所以你必须点击栏上不会导致下拉菜单发生的地方。这在你的测试平台上会更好。)

于 2013-06-13T16:49:10.993 回答