简体   繁体   中英

click outside div to hide, is hiding when clicked inside

I'm trying to create a menu where when a div is clicked it opens another div with the contents. I wanted it close when the user clicked anywhere else. That part seems to work, however it also closes when the div itself is clicked.

The user should be able to click inside the div without it closing,

I was using answers from this question as a guide but they were using ordered lists instead of divs, is there an issue with e.target.class ?

Thanks for any help.

$('.trigger').click(function (e) {
    e.stopPropagation();
    $('.header-menu-container').hide();
    $(this).next('.header-menu-container').slideDown();
});

$(document).click(function (e) {
    if (e.target.class == 'header-menu-container' || e.target.class == 'header-menu-contents') 
        return;
    $('.header-menu-container').slideUp();
});

Please see here: http://jsfiddle.net/75JaR/3/

Change class to className ...

$(document).click(function (e) {
    if (e.target.className == 'header-menu-container' || e.target.className == 'header-menu-contents') return;
    $('.header-menu-container').slideUp();
});

updated jsfiddle...

Incidentally, if you add any further classes to the container and contents elements then the above code won't work. The following code would be more suitable as it will work no matter how many extra classes you add...

$(document).click(function (e) {
    var $this = $(e.target);
    if ($this.hasClass("header-menu-container")) return;
    if ($this.hasClass("header-menu-contents")) return;
    $('.header-menu-container').slideUp();
});

stop the event bubbling up to the document when the div is clicked, then you don't have to do the class check.

http://jsfiddle.net/75JaR/7/

$('.trigger').click(function (e) {
    e.stopPropagation();
    $('.header-menu-container').hide();
    $(this).next('.header-menu-container').click(function(e){
        e.stopPropagation();
    }).slideDown();
});

$(document).click(function (e) {
    $('.header-menu-container').slideUp();
});

改用这个:

if ( $(e.target).is('.header-menu-container') || $(e.target).is('.header-menu-contents') )

Make a click event on the div to stop hiding it once clicked on it.

    $('.trigger').click(function (e) {
       e.stopPropagation();
    $('.header-menu-container').hide();
    $(this).next('.header-menu-container').slideDown();
    });

$(document).click(function (e) {
    if (e.target.class == 'header-menu-container' || e.target.class == 'header-menu-contents') return;
    $('.header-menu-container').slideUp();
    $('.header-menu-container').click(function(){

       return false;
    });
});

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