简体   繁体   中英

Javascript onclick dropdown menu

I'm struggling with this javascript at the moment.

$(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.

I made the body variable trying to fix the problem if you clicked the menu - and then clicked the same link again. 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..

I dont think that running events off of the body tag is the good way to go.

the flow should be..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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