简体   繁体   中英

Close modal when user clicks outside of it, why is there == and not !=?

I looked at some code from here: https://www.w3schools.com/howto/howto_css_modals.asp , but I want to understand why is there == and not != in the folowing part of code:

// Get the modal
var modal = document.getElementById('yourModalId');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

We want to close the window when the outside of the modal is clicked. Why is there an equal sign there than?

Looks like it's because modal is the background, and modal-content is what you think should be the modal.

See the working example here , and notice this block of CSS:

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

Based on the link provided, modal is the lightbox of the modal. (The transparent background) So when a user clicks that, close the modal.

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