2024-06-10 carousel實做輪播,最後一步, 實作dots

2024-06-10 carousel實做輪播,最後一步, 實作dots

html的部份
dots放在button底下同層

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

妝飾 dots

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

.slide-dots {
position: absolute;
bottom: 30px;
width: 100%;
text-align: center;
z-index: 20; /* Ensure dots are above slides and buttons */
}
.slide-dot {
display: inline-block;
width: 10px;
height: 10px;
background-color: gray;
border-radius: 50%;
margin: 5px;
cursor: pointer;
}
.active-dot {
background-color: #1616ed;
}

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
const slideDots = document.querySelector('.slide-dots');

// Generate dots
for (let i = 0; i < imgCount; i++) {
const dot = document.createElement('span');
dot.classList.add('slide-dot');
dot.dataset.index = i;
slideDots.appendChild(dot);
}

// Set the active dot
function setActiveDot(index) {
const dots = document.querySelectorAll('.slide-dot');
dots.forEach(dot => dot.classList.remove('active-dot'));
dots[index].classList.add('active-dot');
}

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

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

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

最後畫面呈現的樣子