본문 바로가기

아래로 스크롤 해주세요!

My Reference Book

-

제가 배웠던것을 한곳에 정리해보았어요!

HTML

HTML 태그 톺아보기

HTML

자세히보기

CSS

CSS 속성 톺아보기

CSS

자세히보기

JAVASCRIPT

JS 실행문 톺아보기

JAVASCRIPT

자세히보기

최신댓글

JS 응용하기

슬라이드 이펙트_03 : JS를 이용해서 translateX로 이미지 슬라이드를 구현해보자!

by C0Di 2022. 9. 1.
728x90

슬라이더 이펙트 03

이번 슬라이드 이펙트_03 예제에서는 현재 값이 이미지 총 갯수와 같아졌을때 시간을 0.7초로 설정 해놓은 상태에서 움직이는 영역(.slider__inner)가 0px 위치로 이동해 슬라이드 효과를 보여주는 예제를 만들어 보도록 하겠습니다!


HTML : 예제용 코드보기

예제 구현을 위한 이미지가 총 5개로 구성된 구조를 만들어 주도록 하겠습니다~~

<body class="img05">
    <!-- header -->
    <header id="header">
        <h1>Javascript Slider Effect03</h1>
        <p>슬라이드 이펙트 - 좌로 움직이기 (연속적으로)</p>
        <ul>
            <li><a href="sliderEffect01.html">1</a></li>
            <li><a href="sliderEffect02.html">2</a></li>
            <li class="active"><a href="sliderEffect03.html">3</a></li>
            <li><a href="sliderEffect04.html">4</a></li>
            <li><a href="sliderEffect05.html">5</a></li>
            <li><a href="sliderEffect06.html">6</a></li>
            <li><a href="sliderEffect07.html">7</a></li>
        </ul>
    </header>

    <!-- main -->
    <main id="main">
        <section id="sliderType01">
            <div class="slider__wrap">
                <div class="slider__img">
                    <div class="slider__inner">
                        <div class="slider"><img src="../../assets/slider/effect_img_01@2x.jpg" alt="이미지1"></div>
                        <div class="slider"><img src="../../assets/slider/effect_img_02@2x.jpg" alt="이미지2"></div>
                        <div class="slider"><img src="../../assets/slider/effect_img_03@2x.jpg" alt="이미지3"></div>
                        <div class="slider"><img src="../../assets/slider/effect_img_04@2x.jpg" alt="이미지4"></div>
                        <div class="slider"><img src="../../assets/slider/effect_img_05@2x.jpg" alt="이미지5"></div>
                        <!-- <div class="slider"><img src="../../assets/slider/effect_img_06@2x.jpg" alt="이미지5"></div> -->
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- footer -->
    <footer id="footer">
        <div class="modal__wrap">
            <div class="modal__btn">소스 보기</div>
            <div class="modal__cont">
                <div class="modal__box">
                    <div class="title">
                        <span class="dot" aria-lable="true"></span>
                        <div class="tabs">
                            <div class="active">
                                <span class="favicon" aria-label="true">
                                    <svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true" focusable="false">
                                        <circle cx="9" cy="9" r="9" fill="#fff"></circle>
                                        <path d="M18 9C18 13.9706 15.4688 3.09375 9 10.125C2.53125 17.1562 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="orange"></path>
                                        <path d="M18 9C18 13.9706 14.9062 0.84375 8.29688 6.1875C1.6875 11.5312 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="yellow"></path>
                                      </svg>
                                </span>
                                <em>Javascript</em>
                                <span class="close">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false">
                                        <path d="M12.5 3.5L3.5 12.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                        <path d="M12.5 12.5L3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                      </svg>
                                </span>
                            </div>
                            <div >
                                <span class="favicon" aria-label="true">
                                    <svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true" focusable="false">
                                        <circle cx="9" cy="9" r="9" fill="#fff"></circle>
                                        <path d="M18 9C18 13.9706 15.4688 3.09375 9 10.125C2.53125 17.1562 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="orange"></path>
                                        <path d="M18 9C18 13.9706 14.9062 0.84375 8.29688 6.1875C1.6875 11.5312 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="yellow"></path>
                                      </svg>
                                </span>
                                <em>HTML</em>
                                <span class="close">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false">
                                        <path d="M12.5 3.5L3.5 12.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                        <path d="M12.5 12.5L3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                      </svg>
                                </span>
                            </div>
                            <div>
                                <span class="favicon" aria-label="true">
                                    <svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true" focusable="false">
                                        <circle cx="9" cy="9" r="9" fill="#fff"></circle>
                                        <path d="M18 9C18 13.9706 15.4688 3.09375 9 10.125C2.53125 17.1562 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="orange"></path>
                                        <path d="M18 9C18 13.9706 14.9062 0.84375 8.29688 6.1875C1.6875 11.5312 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="yellow"></path>
                                      </svg>
                                </span>
                                <em>CSS</em>
                                <span class="close">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false">
                                        <path d="M12.5 3.5L3.5 12.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                        <path d="M12.5 12.5L3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                      </svg>
                                </span>
                            </div>
                        </div>
                        <span class="plus" aria-label="true">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" focusable="false">
                                <path d="M2.5 8H13.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                                <path d="M8 2.5V13.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
                              </svg>
                        </span>
                    </div>
                    <div class="cont">
                        <div style="height: 100%">
<pre><code style="font-family: 'NeoDunggeunmo" class="lauguage-js scroll">
</code></pre>
                        </div>
                        <div style="height: 100%">
<pre><code style="font-family: 'NeoDunggeunmo" class="lauguage-html scroll">
</code></pre>
                        </div>
                        <div style="height: 100%">
<pre><code style="font-family: 'NeoDunggeunmo'" class="lauguage-css scroll">
</code></pre>
                        </div>
                    </div>
                </div>
                <div class="modal__close">
                    <svg width="16" height="16" viewBox="0 0 18 18" fill="none" aria-hidden="true" focusable="false">
                        <circle cx="9" cy="9" r="9" fill="#fff"></circle>
                        <path d="M18 9C18 13.9706 15.4688 3.09375 9 10.125C2.53125 17.1562 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="orange"></path>
                        <path d="M18 9C18 13.9706 14.9062 0.84375 8.29688 6.1875C1.6875 11.5312 0 13.9706 0 9C0 4.02944 4.02944 0 9 0C13.9706 0 18 4.02944 18 9Z" fill="yellow"></path>
                      </svg>
                </div>
            </div>
        </div>
    </footer>

CSS : 예제용 코드보기

크게 특이점은 없지만 각 이미지가 몇번째 이미지인지 알 수 있도록 [nth:child]를 사용하여 각 이미지에 content로 이름을 적어줍니다.

/* slider */
    .slider__wrap {
        /* background: #000; */
        width: 100%;
        height: 100vh;
        /* background-color: #ccc; */
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .slider__img { /*이미지 보이는 영역 */
        position: relative;
        width: 800px;
        height: 450px;
        overflow: hidden;
    }

    .slider__inner{ /* 이미지를 감싸고 있는 부모 : 움직이는 부분 */
        display: flex;
        flex-wrap: wrap;
        width: 4800px; /* 총 이미지 6개 */
        height: 450px;
        position: relative;
        /* transform: translateX(-800px); */
    }

    .slider { /* 개별적인 이미지 */
        width: 800px;
        height: 450px;
        position: relative;
    }

    .slider::before{
        position: absolute;
        left: 5px;
        top: 5px;
        background: rgba(0,0,0,0.4);
        color: #fff;
        padding: 5px 10px;
        border-radius: 10px;
    }

    .slider:nth-child(1)::before {content: "이미지 1";}
    .slider:nth-child(2)::before {content: "이미지 2";}
    .slider:nth-child(3)::before {content: "이미지 3";}
    .slider:nth-child(4)::before {content: "이미지 4";}
    .slider:nth-child(5)::before {content: "이미지 5";}
    .slider:nth-child(6)::before {content: "이미지 1";}

    /* .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;} */

    @media(max-width: 800px){
        .slider__img{
            width: 400px;
            height: 225px;
        }
    }

자바스크립트 : 예제용 코드보기

이번 자바스크립트에서는 각 이미지가 슬라이드가 가능하게 함과 동시에 현재 값이 이미지 총 갯수와 같아졌을때 다시 처음이미지로 돌리는 방식으로 슬라이드 이펙트를 구현합니다.

const sliderWrap = document.querySelector(".slider__wrap")
const sliderImg = document.querySelector(".slider__img")        //보여지는 영역
const sliderInner = document.querySelector(".slider__inner")    //움직이는 영역
const slider = document.querySelectorAll(".slider")             //각각 이미지 

let currentIndex = 0;                                                   //현재 보이는 이미지
let sliderCount = slider.length;                                        //이미지 갯수
let sliderWidth = sliderImg.offsetWidth;                                //이미지 가로값
let sliderClone = sliderInner.firstElementChild.cloneNode(true);        //첫번째 이미지 복사
sliderInner.appendChild(sliderClone);                                   //첫번째 이미지를 마지막에 넣어줌

function sliderEffect(){
    currentIndex++;                                                     //슬라이더 이펙트가 실행될때마다 currentIndex(현재 보여주는 이미지 값)을 1씩 즐가
    sliderInner.style.transition = "all 0.6s"                           //움직이는 영역의 트랜지션은 0.6초로 설정

    sliderInner.style.transform="translateX(-"+ sliderWidth * currentIndex +"px)";//이미지 가로값에 현재 이미지 번호를 곱해서 왼쪽으로 이동시킬 값을 구합니다.

    //자미가 사진에 위치 했을 때
    if(currentIndex==sliderCount){                          //현재 값이 이미지 갯수와 같아졌을때
        setTimeout(()=>{                                    //시간을 0.7초로 설정하고
            sliderInner.style.transition = "0s";            //sliderInner의 trasition을 0초로 초기화 한 후
            sliderInner.style.transform = "translateX(0px)";//sliderInner를 0px 위치로 이동시킨다
        }, 700)
        currentIndex = 0;                                   //현재 값 0으로 초기화

    }
}

    setInterval(sliderEffect, 2000)                             //슬라이더 이펙트 함수 실행은 2초마다

번외 : 소스보기 버튼 구현

효율적인 코드 작성을 위해 소스보기 버튼은 따로 'common.js'라는 파일로 저장해 불러와 사용하였습니다.

// 모달
const modalBtn = document.querySelector(".modal__btn");
const modalClose = document.querySelector(".modal__close");
const modalCont = document.querySelector(".modal__cont");


//보이기
modalBtn.addEventListener("click", ()=>{
    modalCont.classList.add("show");
    modalCont.classList.remove("hide");
})


//숨기기
modalClose.addEventListener("click", ()=>{
    modalCont.classList.add("hide");
})


// 탭 메뉴
const tabBtn = document.querySelectorAll(".modal__box .tabs > div")
const tabCont = document.querySelectorAll(".modal__box .cont > div")

tabBtn.forEach((e, i) => {
    e.addEventListener("click", (event) => {
        event
            .preventDefault(); //상단의 event 라는 장소에 클릭 값이 저장되는데 그 장소에 지정한 이름 뒤에 .preventDefault()를 적어 막는다

        //li의 클래스로 붙어있던 active를 모두 제거했습니다.
        //e라고 지정해 li를 불러와도 괜찮고 li를 적어 태그를 바로 지정해도 괜찮다.
        tabBtn.forEach(e => {
            e.classList.remove("active")
        })

        //내가 클릭한 버튼(e=li)에 active를 추가해봄
        e.classList.add("active")

        //버튼을 클릭하면 모든 자식 박스를 숨김
        tabCont.forEach(div => {
            div.style.display = "none"
        })

        //[i]클릭한 버튼과 [i]박스를 보이게 함
        tabCont[i].style.display = "block";
    })
})

구현예제

너무나도 멋있는 슬라이더 이펙트~~~ 완성~~~! 멋지죠?

728x90
반응형

댓글

#HASH_TAGS

-

1

다크모드 오징어 두마리 포획 완료 JQuery 오늘도 웹표준은.. 멈추지 않는 ' j ' 시리-즈 이건 또 뭐람 화사한가요? 선택해주세요 오징어 한마리 수확 완료! 오징어 1Kg 당 3000원 슬라이드 결과 : 월요일 scroll-snap-align Method ImageSlideEffect 메서드 코딩 울적하니 꽃을 달아봤습니다 공부 HTML 코드 오늘 조업 마감했습니다. 내일은 즐거운 월요일 제이쿼리 필터선택자 오늘은 내가바로 오징어! scroll-snap-type 숙제가 다양해서 너무 좋아요