我正在尝试使用html,css和纯JavaScript完全从头开始创建幻灯片,但是我不知道该怎么做,因此当我单击其中一个幻灯片指示器时,setInterval()重置其计时器(按顺序这样就可以更改幻灯片而无需直接切换到下一个幻灯片,例如,仅剩1秒钟)
我曾尝试使用clearInterval()重置计时器,然后重新激活setInterval(),但是当我单击幻灯片放映指示器之一时,幻灯片会在随机时刻开始更改(它们不遵循计时器的6000ms计时器) SetInterval()由于某种原因)。
var slides = document.querySelectorAll(".slide");
var dots = document.querySelectorAll(".dot");
function removeClass() {
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
}
}
function removeNext() {
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('next');
}
}
function slideshow() {
currentSlide = document.querySelector(".active");
nextSlide = currentSlide.nextElementSibling;
if (nextSlide != null) {
removeClass();
nextSlide.classList.add('next');
nextSlide.classList.add('active');
} else {
removeClass();
slides[0].classList.add('next');
slides[0].classList.add('active');
}
removeNext();
}
var slideDelay = setInterval(slideshow, 6000);
document.addEventListener("click", function(event){
if (event.target.className == "dot") {
removeClass();
var dotAttrValue = event.target.getAttribute('data-slide-to');
slides[dotAttrValue-1].classList.add('active');
clearInterval(slideDelay);
var slideDelay = setInterval(slideshow, 6000);
}
});
答案 0 :(得分:2)
具有两个var声明会创建两个单独的间隔。只需摆脱第二个,就可以了。
var slides = document.querySelectorAll(".slide");
var dots = document.querySelectorAll(".dot");
function removeClass() {
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('active');
}
}
function removeNext() {
for (var i = 0; i < slides.length; i++) {
slides[i].classList.remove('next');
}
}
function slideshow() {
currentSlide = document.querySelector(".active");
nextSlide = currentSlide.nextElementSibling;
if (nextSlide != null) {
removeClass();
nextSlide.classList.add('next');
nextSlide.classList.add('active');
} else {
removeClass();
slides[0].classList.add('next');
slides[0].classList.add('active');
}
removeNext();
}
var slideDelay = setInterval(slideshow, 6000);
document.addEventListener("click", function (event) {
if (event.target.className == "dot") {
removeClass();
var dotAttrValue = event.target.getAttribute('data-slide-to');
slides[dotAttrValue - 1].classList.add('active');
clearInterval(slideDelay);
slideDelay = setInterval(slideshow, 6000);//Var removed from here.
}
});