JS

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

ryeonng 2024. 8. 2. 16:16

 

<!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; /* 공간 크기 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="felx-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>

'JS' 카테고리의 다른 글

JS 이벤트 처리 - Ajax 와 Fetch  (0) 2024.08.02
JS 이벤트 처리 - Promise  (0) 2024.08.02
JS 이벤트 처리 - 이미지 토글  (0) 2024.08.02
JS 이벤트 처리 - 반복문과동적생성  (0) 2024.08.01
JS 이벤트 처리 - forms  (0) 2024.08.01