JS 이벤트 처리 - 6(배너변경하기)

1. 무한 슬라이더를 위한 코드 작성하기

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .flex-container {
        display: flex;
        height: 200px;
        /* 이미지가 벗어나는 부분 숨기기 */
        overflow: hidden;
      }
      .flex-item {
        flex: 1;
        display: flex;
        justify-content: center;
        position: relative;
      }
      .flex-item img {
        width: 100%;
        height: 200px;
        position: absolute;
        top: 0;
        left: 0;
        visibility: hidden;
      }
      .flex-item img.active {
        opacity: 1;
        visibility: visible;
      }
    </style>
  </head>
  <body>
    <div class="flex-container">
      <div class="flex-item">
        <button class="button prev-btn">prev</button>
      </div>
      <div class="flex-item">
        <img src="../ch01/images/images1.png" alt="" />
        <img src="../ch01/images/images2.png" alt="" />
      </div>
      <div class="flex-item">
        <button class="button next-btn">next</button>
      </div>
    </div>
    <script>
      let images = document.querySelectorAll(".flex-item img");
      let currentIndex = 0;
      images[currentIndex].classList.add("active");
      document.querySelector(".prev-btn").addEventListener("click", () => {
        // 현재 active 클래스를 가진 img 에서 active 클래스 제거 후 -1
        images[currentIndex].classList.remove("active");
        currentIndex--;
        if (currentIndex < 0) {
          currentIndex += images.length;
        }
        images[currentIndex].classList.add("active");
      });
      document.querySelector(".next-btn").addEventListener("click", () => {
        // 현재 active 클래스를 가진 img 에서 active 클래스 제거 후 +1
        images[currentIndex].classList.remove("active");
        currentIndex++;
        if (currentIndex > images.length - 1) {
          currentIndex = 0;
        }
        images[currentIndex].classList.add("active");
      });
    </script>
  </body>
</html>

JS 목차로 돌아가기