자바스크립트로 fade 효과있는 갤러리 만들기

위의 이미지와 같은 갤러리를 만드는 방법이다! 이미지를 사용하려면 div안에 img를 넣어주면 된다.

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
    <style>
      .box {
        margin-top: 200px;
        margin-left: 200px;
        height: 200px;
        width: 200px;
      }

      .one {
        background-color: red;
      }

      .two {
        background-color: aqua;
      }

      .three {
        background-color: blue;
      }

      .hidden {
        display: none;
      }

      .fade-out {
        animation: fadeout 3s;
      }

      .fade-in {
        animation: fadein 3s;
      }

      @keyframes fadein {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }

      @keyframes fadeout {
        from {
          opacity: 1;
        }
        to {
          opacity: 0;
        }
      }
    </style>
  </head>

  <body>
    <div class="wrap">
      <div class="box one"></div>
      <div class="box two hidden"></div>
      <div class="box three hidden"></div>
    </div>
    <script>
      let count = 1;

      const boxOne = document.querySelector('.box.one');
      const boxTwo = document.querySelector('.box.two');
      const boxThree = document.querySelector('.box.three');

      function changeImg() {
        count += 1;
        let currentBox, nextBox;
        if (count % 3 === 2) {
          currentBox = boxOne;
          nextBox = boxTwo;
        } else if (count % 3 === 0) {
          currentBox = boxTwo;
          nextBox = boxThree;
        } else {
          currentBox = boxThree;
          nextBox = boxOne;
        }

        function hideCurrentBox() {
          currentBox.classList.add('hidden');
        }

        function showNextBox() {
          nextBox.classList.remove('hidden');
          nextBox.classList.add('fade-in');
        }
        currentBox.classList.remove('fade-in');
        currentBox.classList.add('fade-out');
        setTimeout(hideCurrentBox, 3000);
        setTimeout(showNextBox, 4000);
      }

      function foo() {
        changeImg();
        setTimeout(foo, 7000);
      }

      setTimeout(foo, 5000);
    </script>
  </body>
</html>

By dororok

Leave a Reply

Your email address will not be published. Required fields are marked *