포트폴리오 제작과정을 잊지 않기 위해 블로그에다 기능 하나하나 올려보기로 하였다!
하루에 하나씩 올려보는 것이 목표이다
완벽하게 만들 수 있을진 몰라도 할 수 있는 한 계속해서 디자인을 다듬고 기능을 추가할 예정이다..!
홈페이지에 단골로 등장하는 슬라이드
나도 한 번 만들어 보았다. ↓
<div class="slider">
<div class="slides">
<div class="slide">
<img src="./slide/slide1.jpg" alt="이미지 1">
</div>
<div class="slide">
<img src="./slide/slide2.jpg" alt="이미지 2">
</div>
<div class="slide">
<img src="./slide/slide3.jpg" alt="이미지 3">
</div>
</div>
<button class="prev" onclick="changeSlide(-1)">
<span class="material-symbols-outlined">
arrow_back_ios
</span>
</button>
<button class="next" onclick="changeSlide(1)">
<span class="material-symbols-outlined">
arrow_forward_ios
</span>
</button>
</div>
슬라이드를 만들기 전에 ↓
슬라이드 기능을 지원하는 번들을 꼭 넣기
(직접 하나하나 만들어도 되긴 하는데 시간적으로나 편의성으로나 외부에서 만들어주는 게 더 편하다고 판단)
<div class="slider"> : 화면에 띄울 영역
<div class="slides"> : 슬라이드 요소들을 이동시키는 <div>이다.
<div class="slide"> : 슬라이드 요소들로, 태그 안에 띄울 이미지들을 넣는다.
<img src="./slide/slide1.jpg" alt="이미지 1"> : 화면에 띄울 이미지들
이미지 3개를 넣고싶으면 slide를 slider 안에 3개 넣으면 된다.
+ 이전 버튼과 다음 버튼을 넣고 싶다?
<button class="prev" onclick="changeSlide(-1)">
<span class="material-symbols-outlined">
arrow_back_ios
</span>
</button>
이전 버튼 + 부둥호 표시 아이콘(arrow_back_ios)
<button class="next" onclick="changeSlide(1)">
<span class="material-symbols-outlined">
arrow_forward_ios
</span>
</button>
다음 버튼 + 부둥호 표시 아이콘(arrow_back_ios)
부둥호 아이콘은 무료로 받은 아이콘이다.
작성이가 쓴 아이콘 소스는
다른 아이콘 다운로드하고 싶으면 ↓
https://fonts.google.com/
Browse Fonts - Google Fonts
Making the web more beautiful, fast, and open through great typography
fonts.google.com
function changeSlide(direction) {
showSlide(currentSlide + direction); // 현재 슬라이드에서 주어진 방향만큼 이동한 슬라이드를 표시
}
이 함수는 슬라이드 순서에 대한 함수이다.
changeSlide 함수를 쓰기 전에 showSlide에 대해 보자면 ↓
function showSlide(index) {
const slides = document.querySelactorAll('.slide'); // 모든 슬라이드
if (index >= slides.length) currentSlide = 0; // 인덱스가 슬라이드의 길이를 초과하면 첫 번째 슬라이드
else if (indax < 0) currentSlide = slides.length - 1; //인덱스가 0보다 작으면 마지막 슬라이드로 이동
else currentSlide = index; //그 외에는 주어진 인덱스로 슬라이드를 설정
const offset = -currentSlide * 100; //슬라이드의 오프셋을 계산, 100%씩 이동하도록 설정.
document.querySelector('.slides').style.transform = `translateX(${ofset}%)`; // 슬라이드를 좌우로 이동
}
현재 슬라이드를 ↓
// 현재 슬라이드 인덱스
let currantSlide = 0;
로 선언해준다.
그리고 제일 중요한 슬라이드 선언 함수 ↓
new Swiper('.promotion .swiper-container', {
slidesPerView: 3, // 한 번에 보여줄 슬라이드 개수
spaceBetween: 10, // 슬라이드 사이 여백
centeredSlides: true, // 1번 슬라이드가 가운데 보이기
loop: true, // 무한 반복
autoplay: {
delay: 7000 // 자동 변환 7초
},
navigation: { // 이전 & 다음 버튼
prevEl: '.promotion .swiper-prev',
nextEl: '.promotion .swiper-next'
}
});
.promotion 과 .prev, .next는 사용하는 라이브러리로 사용자 지정을 했을 때 슬라이드 기능이 안 먹힌다.
그래서 그.대.로 써야 함
결과물 ↓
슬라이드 속 이미지는 지인에게 부탁한 이미지입니다. 재밌죠? ㅋㅋ
슬라이드 결과물
※ 코드는 공부 목적으로 업로드해놓았습니다.
※ 복붙 X, 눈팅 O
※ 복붙해서 사용해도 작동이 안 될 겁니다.