我有一个用 Javascript、CSS 和 HTML 构建的滑块,没有依赖项。滑块工作正常。
如何在div元素内的Javascript中显示计数器幻灯片编号
.gallery-counter
?
例如,如果总共有 8 张幻灯片,则第一张幻灯片将显示 1/8。
let currentIndex = 0;
document.querySelector('.prev-button').addEventListener('click', () => {
navigate(-1);
});
document.querySelector('.next-button').addEventListener('click', () => {
navigate(1);
});
// Navigation
function navigate(direction) {
const galleryContainer = document.querySelector('.gallery-container');
const totalImages = document.querySelectorAll('.gallery-item').length;
currentIndex = (currentIndex + direction + totalImages) % totalImages;
const offset = -currentIndex * 100;
galleryContainer.style.transform = `translateX(${offset}%)`;
}
// Autoplay
let autoplayInterval = null;
function startAutoplay(interval) {
stopAutoplay();
autoplayInterval = setInterval(() => {
navigate(1);
}, interval);
}
function stopAutoplay() {
clearInterval(autoplayInterval);
}
startAutoplay(3000);
// Stop autoplay when user interacts
document.querySelectorAll('.nav-button').forEach(button => {
button.addEventListener('click', stopAutoplay);
});
<section id="gallery">
<div class="gallery-container">
<figure class="gallery-item">
<img src="img-1.jpg" />
</figure>
<figure class="gallery-item">
<img src="img-2.jpg" />
</figure>
<figure class="gallery-item">
<img src="img-3.jpg" />
</figure>
</div>
<div class="gallery-counter"></div>
<nav class="gallery-navigation">
<button class="nav-button prev-button"><span><</span></button>
<button class="nav-button next-button"><span>></span></button>
</nav>
</section>
我将引入一个新函数
updateSlideDisplay()
来处理此任务。该函数有 2 个参数:当前所在幻灯片的索引和图像总数。然后它会定位您的 gallery-counter
div 并将其内部文本内容设置为我们想要的值。
请注意,我将您的索引值增加 1,因为我们不想将第一张幻灯片显示为 0,而是显示为 1 等。
function updateSlideDisplay(currentIndex, totalImages) {
const counter = document.querySelector(".gallery-counter");
const slideNumber = (currentIndex + 1).toString() + "/" + totalImages.toString();
counter.innerHTML = slideNumber;
}
该函数将从
navigate
函数内部调用,如下所示:
function navigate(direction) {
const galleryContainer = document.querySelector('.gallery-container');
const totalImages = document.querySelectorAll('.gallery-item').length;
currentIndex = (currentIndex + direction + totalImages) % totalImages;
const offset = -currentIndex * 100;
galleryContainer.style.transform = `translateX(${offset}%)`;
updateSlideDisplay(currentIndex, totalImages);
}
请注意,要显示计数器,您必须至少调用一次
navigate
函数。您可以在页面加载时调用该函数来导航到您的第一张幻灯片。
此外,请考虑在
<p>
内添加 gallery-counter
元素,因为直接写入 div
innerHTML 并不是最佳实践。然后在 updateSlideDisplay()
的 querySelector 中,只需将 div 的类名与新 p
元素的类名/id 进行切换即可。