문제

I have this code:

$("a.shownav").on("click", function(){
    $("div.nav").slideToggle();
});

And when I click on the other parts of the page, except for the div.nav part, I want the div.nav part to slideup. I have tried this but it doesn't seem to work:

if ($("div.nav").is(":visible")){
    $("*").not("div.nav").on("click", function(){
        $("div.nav").slideUp();
    });
}

How do I achieve what I want?

도움이 되었습니까?

해결책

You could handle the click event of the document, get the target object, then test if it is the nav div or a child of the nav div. If it is not one of the 2, you can close it.

$(document).on("click", function(e){
    var targ = $(e.target);
     if (!targ.hasClass("nav") && targ.parents(".nav").length < 1) {
        $("div.nav").slideUp();
    }
});

DEMO

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top