Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

Click outside div to hide div in pure JavaScript

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 when I click outside of it.

var popbox = document.getElementById("popbox");

document.getElementById("linkbox").onclick = function () {
    popbox.style.display = "block";
};

???.onclick = function () {
    popbox.style.display = "none";
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the second version which has a transparent overlay as asked by the asker in the comments...

window.onload = function(){
var popup = document.getElementById('popup');
    var overlay = document.getElementById('backgroundOverlay');
    var openButton = document.getElementById('openOverlay');
    document.onclick = function(e){
        if(e.target.id == 'backgroundOverlay'){
            popup.style.display = 'none';
            overlay.style.display = 'none';
        }
        if(e.target === openButton){
         popup.style.display = 'block';
            overlay.style.display = 'block';
        }
    };
};
#backgroundOverlay{
    background-color:transparent;
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    display:block;
}
#popup{
    background-color:#fff;
    border:1px solid #000;
    width:80vw;
    height:80vh;
    position:absolute;
    margin-left:10vw;
    margin-right:10vw;
    margin-top:10vh;
    margin-bottom:10vh;
    z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
    <div id="backgroundOverlay"></div>
    <input type="button" id="openOverlay" value="open popup">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...