[JS] 슬라이더

2022. 5. 23. 09:31·Stack/JavaScript

15slide_left2.html (인디게이터)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        li { list-style: none;}
        #divView {
            width: 600px;
            height: 400px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform:  translate(-50%, -50%);
            overflow: hidden;
        }
        #divs {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            transition: 0.5s;
        }
        .imgdiv {
            position: absolute;
            top: 0;
        }
        /* .imgdiv:nth-child(1) {
            left: 0;
        }
        .imgdiv:nth-child(2) {
            left: 100%;
        }
        .imgdiv:nth-child(3) {
            left: 200%;
        }
        .imgdiv:nth-child(4) {
            left: 300%;
        } */
        .btn {
            width: 60px;
            height: 60px;
            background-color: tomato;
            color: #fff;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            line-height: 60px;
        }
        #prev {
            margin-left: -250px;
        }
        #next {
            margin-left: 250px;
        }
        #indi {
            position: absolute;
            bottom: 0;
            /* background-color: lightblue; */
            width: 100%;
            text-align: center;
            padding: 10px;
        }
        #indi span {
            display: inline-block;
            width: 16px;
            height: 16px;
            background-color: tomato;
            border-radius: 50%;
            margin: 0 6px;
            font-size: 0;
        }
        #indi span.on {
            background-color: #000;

        }
    </style>
</head>
<body>
    <div id="divView">
        <div id="divs">
            <div class="imgdiv"><img src="../images/img_lights1.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights2.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights3.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights4.jpg" alt=""></div>
            <!-- <div class="imgdiv"><img src="../images/img_lights1.jpg" alt=""></div>
            <div class="imgdiv"><img src="../images/img_lights2.jpg" alt=""></div> -->
        </div>
        <div id="prev" class="btn">이전</div>
        <div id="next" class="btn">다음</div>
        <div id="indi"></div>
    </div>
    <script>
        const imgDivs = document.querySelectorAll('.imgdiv');
        const next = document.querySelector('#next');
        const prev = document.querySelector('#prev');
        const indiDiv = document.querySelector('#indi');
        let divLeft = 0;
        let current = 0;
        let indiStr = "";
        // setInterval을 담을 변수
        let timer;
        imgDivs.forEach((imgdiv,index) =>{
            imgdiv.style.left = `${index*100}%`;   // imgdiv.style.left = `${index*100}%`;
            indiStr = indiStr + `<span>${index}</span>`
        })
        indiDiv.innerHTML = indiStr;
        let indi = document.querySelectorAll('#indi span');
        indi[0].classList.add('on');
        console.log(indi);
        // 인디게이터 이벤트 연결
        indiDiv.addEventListener('click', function(e){
            let targetNum = e.target.innerHTML;
            moveDiv(targetNum);
        })
        // document.querySelector('#indi').innerHTML = indiStr;
        // 이전, 다음 버튼 이벤트 연결
        prev.addEventListener('mouseenter', function(){
            stopIt();
        })
        prev.addEventListener('mouseleave', function(){
            startIt();
        })
        prev.addEventListener('click',function(){
            // 이전으로 이동
            // 현재의 이전값을 구함
            let prevNum = current == 0? imgDivs.length-1 : current-1; // imgDivs.length-1 = 3
            moveDiv(prevNum);
        })
        next.addEventListener('mouseenter',function(){
            stopIt();
        })
        next.addEventListener('mouseleave',function(){
            startIt();
        })
        next.addEventListener('click', function(){
            //현재의 다음값을 구함
            let nextNum = current == imgDivs.length-1? 0 : current + 1;
            //다음값으로 이동
            moveDiv(nextNum);
        })
        // div를 이동시키는 함수
        function moveDiv(left){
            document.querySelector('#divs').style.left = `${-(left * 100)}%`;
            current = left;
            console.log(current);
            indi.forEach(ind=>{ind.classList.remove('on');})
            indi[current].classList.add('on');
        }
        // 현재 보고있는 div가 0일 때 이전 3 다음 1
        // 현재 보고있는 div가 1일 때 이전 0 다음 2
        // 현재 보고있는 div가 2일 때 이전 1 다음 3
        // 현재 보고있는 div가 3일 때 이전 2 다음 0
        // 자동이미지 전환 실행함수(setInterval)
        function startIt() {
             // setInterval(함수, 시간)
            timer = setInterval(function(){
            // 3초마다 이미지전환
            // dom요소divs의 left값이 0%, -100%, -200%, -300%, 0, -100% . . .
            divLeft = current === imgDivs.length-1 ? 0 : divLeft + 1;
            moveDiv(divLeft);
            },3000)
        }
        // 자동이미지 전환 멈춤함수(clearInterval)
        function stopIt() {
            clearInterval(timer);
        }
        startIt();
    </script>
</body>
</html>
</body>
</html>

 

15slide2.html (왼쪽으로 이동하는 무한 슬라이더)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        #slide_wrap {
            width: 100%;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #slide_group_view {
            width: 60%;
            height: 40%;
            position: relative;
            overflow: hidden;
        }
        #slide_group{
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background-color: tomato;
        }
        .slide_img {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            left: 0;
            width: 100%;
        }
        #nav {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
        }
        #nav a {
            display: block;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: blueviolet;
            line-height: 50px;
            text-align: center;
            position: absolute;
            color: #fff;
            left: 50%;
            text-decoration: none;
        }
        #nav a.prev {
            margin-left: calc(-30% - 75px);
        }
        #nav a.next {
            margin-left: calc(30% + 25px);
        }
    </style>
</head>
<body>
    <div id="slide_wrap">
        <div id="slide_group_view">
            <div id="slide_group">
                <img src="/images/img_lights1.jpg" alt="" class="slide_img">
                <img src="/images/img_lights2.jpg" alt="" class="slide_img">
                <img src="/images/img_lights3.jpg" alt="" class="slide_img">
                <img src="/images/img_lights4.jpg" alt="" class="slide_img">
            </div>
        </div>
        <div id="nav">
            <a href="#" class="prev">이전</a>
            <a href="#" class="next">다음</a>
        </div>
    </div>
    <script>
        // 변수준비
        const slideGroup = document.querySelector('#slide_group');
        const prevBtn = document.querySelector('.prev');
        const nextBtn = document.querySelector('.next');
        // 노드의 마지막 자식요소
        const lastImg = slideGroup.lastElementChild;
        // 노드의 첫번째 자식요소
        const firstImg = slideGroup.firstElementChild;
        // 노드 복사하기
        let cloneFirst = firstImg.cloneNode(true);
        let cloneLast = lastImg.cloneNode(true);
        
        // 마지막에 추가하기
        slideGroup.append(cloneFirst);
        // 맨앞에 추가하기
        slideGroup.prepend(cloneLast);

        let prev;
        let next;
        let current = 1;

        const slideImgs = document.querySelectorAll('.slide_img');
        // 스타일 작성하기
        // 이미지를 감싸는 div의 크기를 이미지갯수 * 100%로 변경
        slideGroup.style.width = (slideImgs.length) * 100 + '%';
        slideGroup.style.left = -(current*100)+'%';
        // 이미지크기를 100/이미지갯수 %로 변경
        slideImgs.forEach((img,index) => {
            img.style.width = (100 / slideImgs.length) + '%';
            img.style.left = (index * (100 / slideImgs.length)) + '%';
        })

        // 이미지 전환되는 함수
        function slideMove(imgNum) {
            slideGroup.style.transition = '0.5s';
            slideGroup.style.left = -(imgNum*100) + '%';
            current = imgNum;
            console.log(current);
            if(imgNum == 4){
                console.log('마지막 이미지입니다.');
                firstCurrent();
            }
            if(imgNum == 0) {
                console.log('처음 이미지입니다.');
                lastCurrent();
            }
        }
        let timer;
        function startIt() {
            if(timer) stopIt();
            timer = setInterval(function(){
                slideMove(current+1);
            },2000)
        }
        function stopIt(){
            clearInterval(timer);
            console.log('중지');
        }
        startIt();
        function firstCurrent(){
            setTimeout(function(){
                slideGroup.style.transition="0s";
                slideGroup.style.left = -(0*100)+'%';
                current = 0;
            },500)
        }
        function lastCurrent(){
            setTimeout(function(){
                slideGroup.style.transition="0s";
                slideGroup.style.left = -(400)+'%';
                current = 4;
            },500)
        }

        // 이전버튼에 이벤트 연결하기
        prevBtn.addEventListener('mouseenter', stopIt);
        prevBtn.addEventListener('mouseleave', startIt);
        prevBtn.addEventListener('click',function(e){
            e.preventDefault();
            prev = current - 1;
            slideMove(prev);
        })
        // 다음버튼에 이벤트 연결하기
        nextBtn.addEventListener('mouseenter', stopIt);
        nextBtn.addEventListener('mouseleave', startIt);
        nextBtn.addEventListener('click', function(e){
            e.preventDefault();
            next = current + 1;
            slideMove(next);
        })

    </script>
</body>
</html>

'Stack > JavaScript' 카테고리의 다른 글

[JS] 프로토타입  (0) 2022.05.23
[JS] 구조분해 할당  (0) 2022.05.23
[JS] 클래스 (ES6)  (0) 2022.05.20
[JS] HTML 커스텀 속성  (0) 2022.05.20
[JS] 새로운 데이터 타입  (0) 2022.05.19
'Stack/JavaScript' 카테고리의 다른 글
  • [JS] 프로토타입
  • [JS] 구조분해 할당
  • [JS] 클래스 (ES6)
  • [JS] HTML 커스텀 속성
7ingout
7ingout
  • 7ingout
    Hello, 7ingout world!
    7ingout
  • 전체
    오늘
    어제
    • 분류 전체보기 (205)
      • Project (5)
      • Stack (173)
        • React (40)
        • JavaScript (50)
        • TypeScript (14)
        • HTML (11)
        • CSS (31)
        • Spring (9)
        • PHP (15)
        • SQL (3)
        • Python (0)
      • ETC (9)
      • Design (13)
        • Illustrator (6)
        • Photoshop (7)
      • Articloid (4)
        • 7ingout (4)
  • 공지사항

    • ☻
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
7ingout
[JS] 슬라이더
상단으로

티스토리툴바