var slider = document.querySelector('.slider'); var images = slider.querySelectorAll('img'); var dots = slider.querySelectorAll('.dot'); var currentIndex = 0; var interval = 3000; function slide() { // 对当前图片和下一张图片进行操作 var currentImage = images[currentIndex]; var nextIndex = currentIndex + 1; if (nextIndex >= images.length) { nextIndex = 0; } var nextImage = images[nextIndex]; // 切换图片 currentImage.classList.remove('active'); nextImage.classList.add('active'); // 更新索引 currentIndex = nextIndex; // 更新小圆点 dots[currentIndex].classList.add('active'); for (var i = 0; i < dots.length; i++) { if (i !== currentIndex) { dots[i].classList.remove('active'); } } } // 设置定时器 var timer = setInterval(slide, interval); // 点击切换图片 dots.forEach(function(dot, index) { dot.addEventListener('click', function() { clearInterval(timer); currentIndex = index; slide(); timer = setInterval(slide, interval); }); });修正代码
时间: 2023-06-25 15:02:12 浏览: 104
var slider = document.querySelector('.slider');
var images = slider.querySelectorAll('img');
var dots = slider.querySelectorAll('.dot');
var currentIndex = 0;
var interval = 3000;
function slide() {
// 对当前图片和下一张图片进行操作
var currentImage = images[currentIndex];
var nextIndex = currentIndex + 1;
if (nextIndex >= images.length) {
nextIndex = 0;
}
var nextImage = images[nextIndex];
// 切换图片
currentImage.classList.remove('active');
nextImage.classList.add('active');
// 更新索引
currentIndex = nextIndex;
// 更新小圆点
dots[currentIndex].classList.add('active');
for (var i = 0; i < dots.length; i++) {
if (i !== currentIndex) {
dots[i].classList.remove('active');
}
}
}
// 设置定时器
var timer = setInterval(slide, interval);
// 点击切换图片
dots.forEach(function(dot, index) {
dot.addEventListener('click', function() {
clearInterval(timer);
currentIndex = index;
slide();
timer = setInterval(slide, interval);
});
});
阅读全文