我看过一个关于制作 vanilla JS 滑块的教程,我已经理解了整个代码,因为它很简单,但是 1 行代码对我来说没有任何意义,即使您删除了该行代码,滑块也可以完美运行好吧,你能向我解释一下它是做什么的,因为制作视频的人没有解释那行代码的作用。
我不明白的代码行,它在代码中做什么?
setTimeout(() => current.classList.remove('current'));
以及整个 JS 代码
const slides = document.querySelectorAll('.slide');
const next = document.querySelector('#next');
const prev = document.querySelector('#prev');
const auto = false; // Auto scroll
const intervalTime = 5000;
let slideInterval;
const nextSlide = () => {
// Get current class
const current = document.querySelector('.current');
// Remove current class
current.classList.remove('current');
// Check for next slide
if (current.nextElementSibling) {
// Add current to next sibling
current.nextElementSibling.classList.add('current');
} else {
// Add current to start
slides[0].classList.add('current');
}
setTimeout(() => current.classList.remove('current'));
};
const prevSlide = () => {
// Get current class
const current = document.querySelector('.current');
// Remove current class
current.classList.remove('current');
// Check for prev slide
if (current.previousElementSibling) {
// Add current to prev sibling
current.previousElementSibling.classList.add('current');
} else {
// Add current to last
slides[slides.length - 1].classList.add('current');
}
setTimeout(() => current.classList.remove('current'));
};
// Button events
next.addEventListener('click', e => {
nextSlide();
if (auto) {
clearInterval(slideInterval);
slideInterval = setInterval(nextSlide, intervalTime);
}
});
prev.addEventListener('click', e => {
prevSlide();
if (auto) {
clearInterval(slideInterval);
slideInterval = setInterval(nextSlide, intervalTime);
}
});
// Auto slide
if (auto) {
// Run next slide at interval time
slideInterval = setInterval(nextSlide, intervalTime);
}
这是整个代码的链接。 https://codepen.io/bradtraversy/pen/oVPBaa
泛舟湖上清波郎朗
汪汪一只猫
相关分类