Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

javascript - jQuery - Hide a div menu after clicking outside div

I've build a drop down menu at:

http://www.ourbridalsongs.com/new_header/header.php

When you click on the up/down arrow next to the logo - the menu appears - I'd like to make it disappear when clicking anywhere else on the screen - for some reason it's getting stuck and doesn't slide back up.

Can anyone help resolve this!

Here's my script:

$(document).ready(function () {

    $("ul.subnav").parent().append("<span></span>");
    $("ul.topnav li span").click(function () {
        $(this).parent().find("ul.subnav").slideDown('slow').show();
        $(this).parent().click(function () {}, function () {
            $(this).parent().find("ul.subnav").slideUp('slow');
        });
    }).hover(function () {
        $(this).addClass("subhover");
    }, function () {
        $(this).removeClass("subhover");
    });

});

Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's quite simple: bind a function that hides that menu to everything except that menu. To do that bind a click listener to the body element as it's everywhere, also bind a click listener to menu - the last one should just prevent from executing the first one.

$("body").click(function() {
    $("#services-container-id").hide();
});

$("#services-container-id").click(function(e) {
    e.stopPropagation();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...