There is a menu dropdown comprised o开发者_运维知识库f the expand/collapse button (#client-select) and the dropdown menu (.client-select-dd). The menu itself works just fine except that I want it to also be collapsible if the user clicks anywhere outside the menu instead of specifically having to click the button again.
Initially the menu is collapsed, so the first click changes the background on the menu button(#client-select) and makes the dropdown options visible(.client-select-dd). This first click also adds a class to the body(.client-deactivate). Clicking on (#client-select) again collapses the menu and restores the button image-background.
In my mind, clicking on the body while the menu is open (and has the class ".client-deactivate") should collapse the menu and remove .client-deactivate, but clicking on the body does absolutely nothing. Thanks for any help all of you can provide.
$("#client-select").click (function() {
$("body").toggleClass("client-deactivate");
$(".client-select-close").toggleClass("client-select-open");
$(".client-select-dd").toggle();
});
$(".client-deactivate").click (function() {
$(".client-select-open").toggleClass("client-select-close");
$(".client-select-dd").toggle();
});
Figured it out:
$("#client-select").live ('click', function() { $("#client-select").addClass("client-select-open"); $("#client-select").removeClass("client-select-close"); $(".client-select-dd").css("display", "block"); $("body").addClass("client-deactivate"); });
$(".client-deactivate").live('click', function() {
$("#client-select").removeClass("client-select-open");
$("#client-select").addClass("client-select-close");
$(".client-select-dd").css("display", "none");
$("body").removeClass("client-deactivate");
});
This is probably because when the click handler is first read by the browser, there is no ".client-deactivate" class on the body tag. Also, you don't want to toggle anything when you click on the body, because then if the menu is collapsed and you clicked on the body, it would expand the menu. I assume that you only want the body click handler to close the menu if it's already open.
Try changing the second click handler to:
$("body").click(function() {
if($("body").hasClass("client-deactivate") {
$(".client-select-open").toggleClass("client-select-close");
$(".client-select-dd").toggle();
$("body").removeClass("client-deactivate");
}
});
You might also consider replacing these toggle functions with removeClass, just to be sure that clicking on the body doesn't expand the menu... Like if another function were to collapse the menu but doesn't remove the "client-deactivate" class to the body, then clicking on the body would then still have the class name and run the above code, toggling the menu to the open position.
精彩评论