简体   繁体   English

Javascript onclick下拉菜单

[英]Javascript onclick dropdown menu

I'm struggling with this javascript at the moment. 我目前正在为此JavaScript苦苦挣扎。

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

        $("body").mouseup(function () {
            if (visible) {
                $(this).parent().find("ul.subnav").slideUp('slow');
                visible = false;
                $(this).removeClass("clicked-background");
                body = true;
            }
        });

        $("ul.topnav li a").click(function () { //When trigger is clicked...
            var menu = $(this).parent().find('ul.subnav');

            if (!visible && !body) {
                $(this).parent().find("ul.subnav").slideDown('fast').show();
                visible = true;
                $(this).addClass("clicked-background");
            }
            // else if (visible) 
            //{
            //   $(this).parent().find("ul.subnav").slideUp('slow');
            //   visible = false;
            //   $(this).removeClass("clicked-background");
            // }

            body = false;
        });

    });

I wanted to add the feature, so if you clicked outside the menu/navigation the dropdown would hide. 我想添加功能,因此,如果您在菜单/导航之外单击,则下拉菜单将隐藏。 The current problem with this code is, that if you click the menu and then click outside the menu - you have to double click the menu again to get it showen. 此代码的当前问题是,如果您单击菜单,然后在菜单外部单击,则必须再次双击菜单才能显示它。 This is caused by the body variable is set too 'True' ofc. 这是由于将body变量设置得太“ True”的原因。

I made the body variable trying to fix the problem if you clicked the menu - and then clicked the same link again. 如果您单击菜单,然后尝试再次单击相同的链接,则尝试使body变量尝试解决该问题。 The menu would first open correctly, and then close and open again. 菜单将首先正确打开,然后关闭并再次打开。 Soo main problem is. 太主要的问题是。 My navigation open -> closes -> open 我的导航打开->关闭->打开

Don't use global variables. 不要使用全局变量。 Check if the actual element is visible by checking 通过检查来检查实际元素是否可见

.is(':visible');

You can use that on the various selectors you have now. 您可以在现有的各种选择器上使用它。

I would be tempted to use onmouseout of the 'now visible' menu as the event of choice.. 我很想使用onmouseout的“现在可见”菜单作为选择事件。

I dont think that running events off of the body tag is the good way to go. 我不认为从body标签开始运行事件不是好的方法。

the flow should be.. 流量应该是..

click (menu button or link)
show menu
set onmouseout for button and menu on click
onmouseout, remove onmouseout events

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

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