1. 무한 슬라이더를 위한 코드 작성하기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.flex-container {
display: flex;
height: 200px;
/* 이미지가 벗어나는 부분 숨기기 */
overflow: hidden;
}
.flex-item {
flex: 1;
display: flex;
justify-content: center;
position: relative;
}
.flex-item img {
width: 100%;
height: 200px;
position: absolute;
top: 0;
left: 0;
visibility: hidden;
}
.flex-item img.active {
opacity: 1;
visibility: visible;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">
<button class="button prev-btn">prev</button>
</div>
<div class="flex-item">
<img src="../ch01/images/images1.png" alt="" />
<img src="../ch01/images/images2.png" alt="" />
</div>
<div class="flex-item">
<button class="button next-btn">next</button>
</div>
</div>
<script>
let images = document.querySelectorAll(".flex-item img");
let currentIndex = 0;
images[currentIndex].classList.add("active");
document.querySelector(".prev-btn").addEventListener("click", () => {
// 현재 active 클래스를 가진 img 에서 active 클래스 제거 후 -1
images[currentIndex].classList.remove("active");
currentIndex--;
if (currentIndex < 0) {
currentIndex += images.length;
}
images[currentIndex].classList.add("active");
});
document.querySelector(".next-btn").addEventListener("click", () => {
// 현재 active 클래스를 가진 img 에서 active 클래스 제거 후 +1
images[currentIndex].classList.remove("active");
currentIndex++;
if (currentIndex > images.length - 1) {
currentIndex = 0;
}
images[currentIndex].classList.add("active");
});
</script>
</body>
</html>
'JS > JS 작업을 위한 코딩 연습' 카테고리의 다른 글
JS 이벤트 처리 - 8(AJAX 와 Fetch API) (0) | 2024.08.02 |
---|---|
JS 이벤트 처리 - 7(Promise) (0) | 2024.08.02 |
JS 이벤트 처리 - 5(이미지 토글) (0) | 2024.08.01 |
JS 이벤트 처리 - 4(반복문과동적생성) (0) | 2024.07.30 |
JS 이벤트 처리 - 3(forms) (0) | 2024.07.30 |