画像を拡大表示する - Javascript

モーダルウィンドウサンプル

モーダルウィンドウ

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <title>sample</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="modal-wrapper">
    <img src="" alt="" class="modal-image">
  </div>

  <div class="wrapper">
    <img src="images/sample1.jpg" alt="" class="image" data-src="images/sample1.jpg">
    <img src="images/sample2.jpg" alt="" class="image" data-src="images/sample2.jpg">
  </div>

</body>
</html>

style.css

.wrapper img {
  width: 200px;
  cursor: pointer;
}

.modal-wrapper {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0,0,0,0.5);
  pointer-events: none;
  opacity: 0;
  transition: 0.25s ease-out;
}

.modal-wrapper.show {
  opacity: 1;
  pointer-events: all;
}

.modal-image {
  position: absolute;
  max-width: 80%;
  max-height: 80%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  object-fit: cover;
  opacity: 0;
  transition: 0.5s ease-out;
}

.modal-image.show {
  opacity: 1;
}

script.js

window.onload = function(){
  const modalWrapper = document.querySelector('.modal-wrapper');
  const images = document.querySelectorAll('.image');
  const modalImage = document.querySelector('.modal-image');
  const ht = document.documentElement;
  const body = document.body;

  images.forEach(function(image) {
    image.addEventListener('click', function() {
      modalWrapper.classList.add('show');
      modalImage.classList.add('show');

      var imageSrc = image.getAttribute('data-src');
      modalImage.src = imageSrc;
      ht.style.overflow = "hidden";
      body.style.overflow = "hidden";
    });
  });

  modalWrapper.addEventListener('click', function() {
    if (this.classList.contains('show')) {
      this.classList.remove('show');
      modalImage.classList.remove('show');
      ht.style.overflow = "visible";
      body.style.overflow = "visible";
    }
  });
};