jQuery: Hide popup if click detected elsewhere

前端 未结 12 856
情书的邮戳
情书的邮戳 2020-12-02 14:33

I\'m trying to hide a div if the user clicks anywhere BUT the popup OR its children. This is the code I have so far:

$(\"body\").click(function(){
    var $t         


        
12条回答
  •  佛祖请我去吃肉
    2020-12-02 14:49

    I had issues with all of the solutions here, so after some frustration; I approached the problem from a slightly different direction.

    I specifically didn't like attaching click events to the body or document and event.target wasn't reliable enough. I also didn't want to use stopPropagation() as I didn't want to interfere with other events.

    Here's how I solved it, hope it helps:

    Markup


    JavaScript

    function showModal(){ $("#Modal, #ModalBG").show(); }
    
    $("#ModalBG").click(function () { $("#Modal, #ModalBG").hide() });
    


    CSS

    #Modal{
        z-index: 99;
    }
    
    
    #ModalBG{
        opacity: 0;
        position: fixed;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        width: 100%;
        height: 100%;
        z-index: 98;
        display: none;
    }
    

提交回复
热议问题