2024-06-09 carousel實做輪播,第二步, 實作左右鍵

2024-06-09 carousel實做輪播,第二步, 實作左右鍵

html的部份

1
2
 <button class="left-slide-btn"></button>
<button class="right-slide-btn"></button>

CSS 妝飾左右箭頭
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 .left-slide-btn, .right-slide-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
border: none;
color: white;
font-size: 2rem;
padding: 10px;
cursor: pointer;
z-index: 10;
outline: none;
}

.left-slide-btn {
left: 10px;
}

.right-slide-btn {
right: 10px;
}

javascript實作按左右鍵輪播

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const carsouselInner = document.querySelector('.carousel-inner');
const slides = carsouselInner.children;
const imgCount = slides.length;
const slides_position = [];


// Initialize the carousel
function showDefault() {
for (let i = 0; i < imgCount; i++) {
slides[i].style.left = i * 100 + `%`;
slides_position[i] = i * 100;
}
}

function showDefault_left() {
for (let i = 0; i < imgCount; i++) {
slides[i].style.left = slides_position[i] + `%`;
}
}

function skipSlide(targetSlide, dist) {
slides_position.forEach((x, i, positions) => {
positions[i] = x - dist;
slides[i].style.left = `${positions[i]}%`;
});

}

const rightSlideBtn = document.querySelector('.right-slide-btn');
var currentIndex = 0;
rightSlideBtn.addEventListener('click', function () {
let dist = 100;
if (currentIndex < (imgCount - 1)) {
currentIndex += 1;
skipSlide(currentIndex, dist);
} else {
currentIndex = 0;
showDefault();
}
});

const leftSlideBtn = document.querySelector('.left-slide-btn');
leftSlideBtn.addEventListener('click', function () {
let dist = 100;
if (currentIndex === 0) {
currentIndex = imgCount - 1;
showDefault_left();
skipSlide(currentIndex, dist * (imgCount - 1));
} else {
currentIndex -= 1;
skipSlide(currentIndex, -dist);
}
});

// Add click event to dots
slideDots.addEventListener('click', function (e) {
if (e.target.classList.contains('slide-dot')) {
const targetIndex = Number(e.target.dataset.index);
const dist = 100 * (targetIndex - currentIndex);
skipSlide(targetIndex, dist);
currentIndex = targetIndex;
}
});

showDefault();