(function () {
const $imgs = document.querySelectorAll("img");
const $leftArrow = document.querySelector(".fa-arrow-left");
const $rightArrow = document.querySelector(".fa-arrow-right");
const $dots = document.querySelectorAll("li");
let currentIndex = 0;
function previousImg() {
if (currentIndex === 0) {
$imgs[currentIndex].style.order = `${0}`;
currentIndex = 4;
$imgs[currentIndex].style.order = `${-1}`;
} else {
$imgs[currentIndex].style.order = `${0}`;
currentIndex--;
$imgs[currentIndex].style.order = `${-1}`;
}
}
function nextImg() {
if (currentIndex === 4) {
$imgs[currentIndex].style.order = `${0}`;
currentIndex = 0;
$imgs[currentIndex].style.order = `${-1}`;
} else {
$imgs[currentIndex].style.order = `${0}`;
currentIndex++;
$imgs[currentIndex].style.order = `${-1}`;
}
}
$leftArrow.addEventListener(("click"), previousImg);
$rightArrow.addEventListener(("click"), nextImg);
for (let i = 0; i < $dots.length; i++) {
$dots[i].className += ` ${i}`;
}
for (let i = 0; i < $dots.length; i++) {
$dots[i].addEventListener(("click"), (e) => {
$imgs[currentIndex].style.order = `${0}`;
currentIndex = Number(e.target.classList[1]);
$imgs[currentIndex].style.order = `${-1}`;
});
}
})();
์ฒ์ ํ์ ๋๋ ๋ฐ๋ณต์ ์ด์๋ ์ฝ๋๋ค์ ์ต๋ํ for๋ฌธ์ผ๋ก ์ฒ๋ฆฌํ๋ค.
๋น์์ ๋ง์ฐ์ค์ด๋ฒคํธ์ e์ธ์์ ์ ๋ณด๋ฅผ ์ด๋ป๊ฒ ์จ์ผํ ์ง ๋ชฐ๋ผ ํด๋ฆญํ ์ ์ ์ธ๋ฑ์ค๋ฅผ ์ฐพ๋๋ฐ ๊ณ ์ํ๋๋ฐ, ์ด๋ฒ์๋ ํด๋น ์์์ ์์์ ๋ง๋ index๋ฅผ ํด๋์ค์ ๋ฃ์ด์ฃผ๊ณ e.target.classList[1]
๋ก ์ ๊ทผํด ์ฌ์ฉํด์ ํจ์ฌ ์์ํ๋ค.
์ฒ์ ๋ง๋ค์๋ ์ฝ๋๋ ๋ฐ์์ด ๋๋ ธ์๋๋ฐ ์ง๊ธ๊น์ง ๊ณต๋ถํ๊ฑธ๋ก ์๊ฐํด๋ณด๋ฉด, ๋์ style ๋ณํ๋ฅผ ๋๋ฌด ์์ฃผ์ค์ ์ธ๋ฐ์๋ ๋ฆฌํ๋ก์ฐ์ ๋ฆฌํ์ธํธ๊ฐ ๊ณ์ ์ผ์ด๋์ ๊ทธ๋ฐ๊ฒ๊ฐ๋ค. ์ค๋ ๋ง๋ ์ฝ๋๋ ์ง๋๋ฒ๋ณด๋จ ํ์คํ ๋์ style ๋ณํ๊ฐ ์ ๊ฒ๋ค์ด๊ฐ๋ค.
https://github.com/roadzmoon76/Carousel_repeat
https://carousel-repeat.netlify.app/