이미지 슬라이드 - 버튼 추가
<main>
<section id="sliderType01">
<div class="slider__wrap">
<div class="slider__img">
<div class="slider__inner">
<div class="slider"><img src="img/slider_img01.jpg" alt="이미지1"></div>
<div class="slider"><img src="img/slider_img02.jpg" alt="이미지2"></div>
<div class="slider"><img src="img/slider_img07.jpg" alt="이미지3"></div>
<div class="slider"><img src="img/slider_img08.jpg" alt="이미지4"></div>
<div class="slider"><img src="img/slider_img09.jpg" alt="이미지5"></div>
</div>
</div>
<div class="slider__btn">
<a href="#" class="prev">prev</a>
<a href="#" class="next">next</a>
</div>
</div>
</section>
</main>
.slider__wrap {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.slider__img { /* 화면 보이는 구간 */
width: 800px;
height: 480px;
overflow: hidden;
}
.slider__inner { /* 이미지 움직이는 영역 */
display: flex;
width: 4800px; /* 이미지 총 길이 */
transform: translateX(0);
}
.slider {
width: 800px;
position: relative;
}
.slider::before {
position: absolute;
left: 5px; top: 5px;
background: rgba(0,0,0,0.4);
color: #fff;
padding: 5px 10px 3px;
}
.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__btn a {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 100;
width: 50px;
height: 50px;
background: rgba(0,0,0,0.4);
text-align: center;
line-height: 50px;
transition: all 0.2s;
display: block;
color: #fff;
text-decoration: none;
}
.slider__btn a.prev {
left: 0;
}
.slider__btn a.next {
right: 0;
}
.slider__btn a:hover {
background: rgb(241, 96, 86);
}
const sliderWrap = document.querySelector(".slider__wrap");
const sliderImg = document.querySelector(".slider__img"); //이미지 보이는 영역
const sliderInner = document.querySelector(".slider__inner"); //이미지 움직이는 영역
const slider = document.querySelectorAll(".slider"); //5개의 이미지 저장
const sliderBtn = document.querySelector(".slider__btn");
const sliderBtnPrev = sliderBtn.querySelector(".prev");
const sliderBtnNext = sliderBtn.querySelector(".next");
let currentIndex = 0;
let sliderCount = slider.length;
let sliderWidth = sliderImg.offsetWidth;
function gotoSlider(num){
sliderInner.style.transition = "all 400ms";
sliderInner.style.transform = "translateX("+ -sliderWidth * num + "px)";
currentIndex = num;
}
sliderBtnPrev.addEventListener("click", () => {
let prevIndex = (currentIndex + (sliderCount - 1)) % sliderCount;
gotoSlider(prevIndex);
});
sliderBtnNext.addEventListener("click", () => {
let nextIndex = (currentIndex + 1) % sliderCount;
gotoSlider(nextIndex);
});