Click outside div to hide div in pure JavaScript

前端 未结 6 1560
栀梦
栀梦 2020-12-11 02:50

I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.

I\'m not sure how to make the div disappear

6条回答
  •  半阙折子戏
    2020-12-11 03:09

    Okay, here's a jQuery based solution based on any div clicked within the DOM.

    $('div').on('click', function(e){
        var parents = $(e.currentTarget).parents();
        for (var i = 0; i < parents.length; i++) {
            if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') {
                // you are in the popup
            };
        }
        e.stopPropagation();
    });
    

    This looks at your current element, as well as any of the parents, and checks if the id matches up. If divToHide is in the parents() list, then you keep the popup open.

    *NOTE: This requires wrapping your content within a wrapper div or something similar.

提交回复
热议问题