简体   繁体   中英

How to control multiple modal boxes on one webpage?

I'm currently rebuilding my portfolio and have cards for each of the projects that I've worked on, the idea being that when the user clicks on a card it opens a modal box containing more information about the project and a link to it.

Unfortunately, I can't figure out how to have multiple modal boxes on the same page, without writing a new block of code for every single box. I'm guessing I'll need some sort of for loop but I've been experimenting all day and can't find anything that works.

This is the JavaScript I have so far:

 var modal = document.getElementsByClassName("modal")[1]; var card = document.getElementsByClassName("card")[1]; // When the user clicks on the card, open the modal box card.onclick = function() { modal.style.display = "block"; } // When the user clicks anywhere outside of the modal box, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }

Many thanks!

Add a class in your modal something like .modal ;

window.onclick = function(event) {
  if (event.target.classList.contains('modal')) {
      event.target.style.display = 'none';
  }
}

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