예제로 공부하기/슬라이드 효과

슥슥 바뀌는 슬라이드 이펙트

Hyeon been 2023. 4. 10. 12:42

한번씩 읽고 가세요.

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

- Frederick Philips Brooks
Mythical Man-Month 저자
728x90

슬라이드 이펙트 01

html 코드

    <main id="main">
        <div class="slider__wrap">
            <div class="slider__img">
                <div class="slider"><img src="./img/slider01-min.jpg" alt="이미지1"></div>
                <div class="slider"><img src="./img/slider02-min.jpg" alt="이미지2"></div>
                <div class="slider"><img src="./img/slider03-min.jpg" alt="이미지3"></div>
                <div class="slider"><img src="./img/slider04-min.jpg" alt="이미지4"></div>
                <div class="slider"><img src="./img/slider05-min.jpg" alt="이미지5"></div>
            </div>
        </div>
    </main>


이미지를 5개를 넣기 위해 div박스 5개를 만들어 줍니다.

        .slider__wrap {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .slider__img {
            position: relative;
            width: 800px;   
            height: 450px;
            overflow: hidden;
        }
        .slider {
            position: absolute;
            left: 0;
            top: 0;
            transition: all 0.4s;
        }
        .slider::before {
            position: absolute;
            left: 5px;
            top: 5px;
            background: rgba(0,0,0,0.4);
            color: #fff;
            padding: 5px 10px;
        }
                .slider:nth-child(1) {z-index: 5;}
        .slider:nth-child(2) {z-index: 4;}
        .slider:nth-child(3) {z-index: 3;}
        .slider:nth-child(4) {z-index: 2;}
        .slider:nth-child(5) {z-index: 1;}

제일 큰 박스인 slider__wrap에 width,height 값을 설정해 준 뒤 display : flex로  사진들을 정렬해줍니다.

그리고 align - item,justify -content 를 각 각 센터로 설정해주어 가운데로 오게 해줍니다.

그 아래있는 박스인 slider__img 에게 position-relative와 width,height 를 설정해줍니다.

그 아래 박스 이미지인 slider에게 position-absolute 를 주어 이미지를 고정시켜줍니다. 

그럼 이미지 5개 가 겹쳐 하나의 이미지만 보이게 됩니다.

마지막으론 각 이미지의  번호를 매겨 z-index 값을 줘 겹쳐있는 이미지의 z축으로 순서를 나눠줍니다.

<script>
        //선택자
        const sliderWrap = document.querySelector(".slider__wrap")
        const sliderImg = sliderWrap.querySelector(".slider__img")
        const slider = sliderWrap.querySelectorAll(".slider")

        let currentIndex = 0;   //현재보이는 이미지
        let sliderCount = slider.length;  //이미지 갯수
        let sliderInterval = 3000; //이미지 변경 시간
        setInterval( () => {
            // 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 // currentIndex
            // 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 // nextIndex
            let nextIndex = (currentIndex + 1) % sliderCount;

            slider[currentIndex].style.opacity = "0" 
            slider[nextIndex].style.opacity = "1"

            currentIndex = nextIndex;

            console.log(currentIndex);

        }, sliderInterval)

            // slider[0].style.opacity = "0"    //첫번째 이미지를 안보이게 
            // slider[1].style.opacity = "1"  //두번째 이미지를 보이게

            // slider[1].style.opacity = "0"    //두번째 이미지를 안보이게 
            // slider[2].style.opacity = "1"  //세번째 이미지를 보이게
            
            // slider[2].style.opacity = "0"    //세번째 이미지를 안보이게 
            // slider[3].style.opacity = "1"  //네번째 이미지를 보이게

            // slider[3].style.opacity = "0"    //네번째 이미지를 안보이게 
            // slider[4].style.opacity = "1"  //다섯번째 이미지를 보이게

            // slider[4].style.opacity = "0"    //다섯번째 이미지를 안보이게 
            // slider[0].style.opacity = "1"  //첫번째 이미지를 보이게
    </script>

slider__wrap,slider__img ,slider 을 각각의 변수로 설정하여 선택자를 만들어주고

let currentIndex = 0; //현재보이는 이미지

let sliderCount = slider.length; //이미지 갯수

let sliderInterval = 3000; //이미지 변경 시간

현재 이미지와 ,이미지의 수 ,변경 시간을 설정해줍니다.

 

그 후 초마다 반복되는 setInterval를 사용하여 그 안에 어떤것이 반복 되게 할 지  넣어줍니다.

첫번째 이미지가 사라지면 다음 이미지가 나오게 해줄것이고

두번째 이미지가 사라지면 다음인 세번째 이미지가 나오게 해주는걸 반복 할 것입니다.

slider[currentIndex].style.opacity = "0"     현재 이미지가 사라지게          

slider[nextIndex].style.opacity = "1"          다음 이미지가 나타나게

한 다음 넘어간 다음 이미지가 현재가 되기위해

currentIndex = nextIndex; 를 넣어줍니다.

let nextIndex = (currentIndex + 1) % sliderCount; 까지 넣어주어야 현재이미지(currentIndex)가 +1 이되고 

4가 되었을 때 다시 0이 될 수 있게 이미지 갯수 (sliderCount) 를 나눈 뒤 나머지 값을 가져옵니다 %

 

추가 미션

1번도 2,3번과 동일하게 

GSAP와jQuery 로 만들기

GSAP

    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
    <script>
        setInterval(() => {
            let nextIndex = (currentIndex + 1) % sliderCount;

            gsap.to(slider[currentIndex], { opacity: 0 });
            gsap.to(slider[nextIndex], { opacity: 1 });
            currentIndex = nextIndex;
        }, sliderInterval)
    </script>

GSAP를 사용하려면 일단 라이브러리를 가져와야한다.

그  다음 똑같이 setInterval을 써주고 nextIndex를  설정해 줍니다.

gsap를 사용하려면 gsap.to를 사용하고 slider 중 현재 이미지 [currentIndex]를 선택 한 후 {} 괄호안에 적용할 효과

opacity를 설정 해줍니다.

똑같이 nextIndex 의 opacity를 1로 설정해줍니다.

 currentIndex = nextIndex;는 javascript 방식 과 동일 합니다.

jQuery

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        setInterval(() => {
            nextIndex = (currentIndex + 1 ) % $(".slider").length;

            $(slider[currentIndex]).animate({opacity:0}, 1000)
            $(slider[nextIndex]).animate({opacity:1}, 1000)
            
            currentIndex = nextIndex;

        }, sliderInterval)
    </script>

jQuery 로 라이브러리 부터 가져온 후

 

$(slider[currentIndex])에 animate 를 주어 opacity를 조정 해준 후 몇초 만에 opacity가 적용될지 시간을 적어 줍니다.

1000이라고 적용해서 1000밀리초(또는 1초) 라는 시간을 거쳐 opacity 0로 만들어줍니다.

$(slider[nextIndex]) 도 동일하게 적용하며 opacity를 1로 적용해 currentIndex가 0이 되고 nextIndex1이 되게 해줍니다.