자바스크립트 이미지 슬라이드 버튼 - jabaseukeulibteu imiji seullaideu beoteun

종다이의 한걸음 한걸음씩

개발/프론트엔드

[JavaScript & Jquery] 자바스크립트 슬라이드 만들기(기본틀)

종다이 2021. 5. 26. 18:26

웹 페이지를 보시면 다양한 슬라이드를 많이 볼 수 있을 텐데요 

그런 슬라이드들을 어떻게 만드는지 순수 자바스크립트만으로 하나, 제이쿼리를 이용한 거 하나,

이렇게 2가지 방법으로 기본틀을 만들어 보겠습니다.

1. 순수 JavaScript 만으로

HTML

자바스크립트 이미지 슬라이드 버튼 - jabaseukeulibteu imiji seullaideu beoteun

CSS

html,body{ margin:0;}
#container{ width: 640px; margin: 0 auto;}
h2{ text-align: center;}
.album{height: 400px; width: 100%; overflow: hidden;} /* overflow 되면 숨긴다*/
.images{ 
    display: flex; height: 400px; width: 2560px;
    transition-property: transform; /* transform 속성에대해, js코드에 의해 transform 스타일 추가된다*/
    transition-duration: 1s; /* transition 지속시간 */
}
.image{width: 640px; height: 400px;}
.image:nth-child(1){background-color: tomato;}
.image:nth-child(2){background-color: teal;}
.image:nth-child(3){background-color: orange;}
.image:nth-child(4){background-color: green;}
button{
    width: 100px; height: 30px; border:none;
    color: white; background-color: blueviolet;
}
button:disabled{ /* disabled 된 버튼 */
    background-color: gray;
}
.prev{ float:left}
.next{ float:right}

JavaScript

let curPos= 0; // 현재 보고 있는 이미지의 인덱스 번호!
let position = 0; // 현재 .images 의 위치값!
const IMAGE_WIDTH = 640; // 한번 움직일 때 이동해야 할 거리!

// 요소 선택
const prevBtn = document.querySelector(".prev")
const nextBtn = document.querySelector(".next")
const images = document.querySelector(".images")

function prev(){
    if(curPos > 0){
    nextBtn.removeAttribute("disabled") /* disabled 속성 제거*/
    position += IMAGE_WIDTH /* position 값 증가 */
    
    images.style.transform = `translateX(${position}px)` /* images 스타일 transform, x축 변경*/
    curPos -= 1; /* curPos 값 감소*/
    }
    if(curPos == 0){ /* 이미지 index값 0 되면 prev 못하게 */
        prevBtn.setAttribute("disabled", 'true')
    }
 }
function next(){ 
    if(curPos < 3){
        prevBtn.removeAttribute("disabled")
        position -= IMAGE_WIDTH
        /*
            트랜스폼(변형)의 네가지 속성값(함수)
            - scale() : 확대 또는 축소
            - translate() : 위치 이동
            - rotate() : 회전시키기
            - skew() : 요소 비틀기
        */
        images.style.transform = `translateX(${position}px)`
        curPos += 1;  
    }
    if(curPos == 3){
        // 뒤로 못 가게 하기
        nextBtn.setAttribute("disabled", 'true') // 못 누르는 버튼이 됨
    }
}
// 초기 랜더링 시 최초 호출 함수의 관습적 이름
function init(){
    // 앞으로 가기는 처음부터 못누르게!
    prevBtn.setAttribute("disabled", 'true')
    prevBtn.addEventListener("click", prev)
    nextBtn.addEventListener("click", next)
}

init();
자바스크립트 이미지 슬라이드 버튼 - jabaseukeulibteu imiji seullaideu beoteun

2. Jquery 사용

HTML

자바스크립트 이미지 슬라이드 버튼 - jabaseukeulibteu imiji seullaideu beoteun

CSS

#container{
    position: relative; /* 컨테이너는 포지션 요소다*/
}
h2{
    text-align: center;
}
.items{
    height: 400px; display: flex;
    justify-content: center; align-items: center;
}
.item{
    height: 400px; display: flex;
    justify-content: center; align-items: center;
    display: none;
}
.active{
    display: flex;
    height: 400px; width: 600px; background-color: brown;
    color: white;
}
button, button:active, button:focus{
    position : absolute; /* 문서 흐름에서 제외되고, 상위 포지션 요소 기준으로 배치 */
    top: 45%;
    transform: translateY(-50%);
    width: 50px; height: 20px;
    border: none; background-color: coral; color: white; outline: none;
}
.next{
    right: 0; /* next 버튼 오른쪽으로 */
}
.stepper{
    margin-top: 15px;
    display: flex;
    justify-content: center;
}
.step{
    width: 20px; height: 20px;
    border-radius: 50%;
    background-color: gray;
    margin: 0 6px;
}
.active-step{
    background-color: brown;
}

JavaScript

let curPos = 0; // 현재 보이는 요소의 인덱스 번호

function prev(){
    if(curPos > 0){
        $("button").removeAttr("disabled") // 모든 버튼 사용할 수 있게!
        // toggleClass : 클래스가 있으면 제거, 없으면 생성!
        $($(".item")[curPos]).toggleClass("active")
        $($(".step")[curPos]).toggleClass("active-step")
        $(".item").hide();
        curPos -= 1;
        $($(".item")[curPos]).toggleClass("active")
        $($(".step")[curPos]).toggleClass("active-step")
        $(".active").fadeIn(800); // 새로운 액티브 요소만 스르륵 나타난다
    }
    if(curPos == 0){
        $(".prev")[0].setAttribute("disabled",'true')
    }
}
function next(){
    if(curPos < 3){
        $("button").removeAttr("disabled")
        $($(".item")[curPos]).toggleClass("active")
        $($(".step")[curPos]).toggleClass("active-step")
        $(".item").hide();
        curPos += 1;
        $($(".item")[curPos]).toggleClass("active")
        $($(".step")[curPos]).toggleClass("active-step")
        $(".active").fadeIn(800); 
    }
    if(curPos == 3){
        $(".next")[0].setAttribute("disabled",'true')
    }
}
function init(){
    $(".item").hide()
    $(".active").show()
    $(".prev").click(prev)
    $(".next").click(next)
}
$(document).ready(function(){

    init();
}
자바스크립트 이미지 슬라이드 버튼 - jabaseukeulibteu imiji seullaideu beoteun

이렇게 기본틀을 만들어 봤는데요

여기서 추가하고 싶은 기능이 있으면 추가해서 더 다채로운 슬라이드를 만들 수 있을것 같네요.