본문 바로가기

JS

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

<!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;
            opacity: 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 class="active"  src="../ch01/images/image1.png"  alt="">
            <img src="../ch01/images/image2.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; 

        document.querySelector(".prev-btn").addEventListener('click', () => {

            // 현재 active 클래스를 가진 이미지를 제거 
            images[currentIndex].classList.remove("active");

            currentIndex = currentIndex - 1; 
            if(currentIndex < 0) {
                currentIndex += images.length;
            }

            // 새로운 currentIndex 값으로 지정된 녀석을 활용해서 해당 이미지에 클래스 속성 active 를 추가한다. 
            images[currentIndex].classList.add("active");
           
        });

        document.querySelector(".next-btn").addEventListener('click', () => {
             // 현재 active 클래스를 가진 이미지를 제거 
             images[currentIndex].classList.remove("active");

             currentIndex =  currentIndex + 1; 
             if(currentIndex > images.length - 1) {
                currentIndex -=  images.length;
             }
             images[currentIndex].classList.add("active");
        });
        
    </script>
</body>
</html>
728x90