[英]How do i use setInterval for a carousel?
I'm trying to make my carousel autoplaying by using the setInterval function, but I've been getting no luck.我正在尝试使用 setInterval 函数使我的轮播自动播放,但我一直没有走运。
I tried calling the carousel function in setInterval function at the end, but its not working.. what did i do wrong?最后我尝试在 setInterval 函数中调用 carousel 函数,但它不起作用..我做错了什么?
Here is the sandbox https://codesandbox.io/s/slider-7ph05?file=/src/index.js这是沙箱https://codesandbox.io/s/slider-7ph05?file=/src/index.js
Here are my JS code:这是我的JS代码:
const slides = document.querySelectorAll(".slide");
const prevBtn = document.querySelector(".prevBtn");
const nextBtn = document.querySelector(".nextBtn");
// Inline callback function
// forEach(function(element, index, array){ ... })
slides.forEach(function (slide, index) {
slide.style.left = `${index * 100}%`;
// console.log(slide);
// console.log(index);
// console.log(array);
});
let count = 0;
nextBtn.addEventListener("click", function () {
count++;
carousel();
});
prevBtn.addEventListener("click", function () {
count--;
carousel();
});
function carousel() {
slides.forEach(function (slide) {
if (count > slides.length - 1) {
count = 0;
}
if (count < 0) {
count = slides.length - 1;
}
slide.style.transform = `translateX(-${count * 100}%)`;
// console.log(slides.length);
// console.log(slide);
// console.log(count);
});
}
setInterval(carousel, 3000);
You don't seem to be incrementing the count
variable in setInterval
nor invoking the carousel
function like you do, when the next or previous button is pressed.当按下下一个或上一个按钮时,您似乎没有增加
setInterval
的count
变量,也没有像您那样调用carousel
功能。 Update your setInterval
to increment the counter and invoke the carousel
function.更新您的
setInterval
以增加计数器并调用carousel
函数。
setInterval(()=>{
count++ //increment the counter
carousel() //call the function
}, 3000);
Your index file should then look something like this:您的索引文件应该如下所示:
const slides = document.querySelectorAll(".slide");
const prevBtn = document.querySelector(".prevBtn");
const nextBtn = document.querySelector(".nextBtn");
// Inline callback function
// forEach(function(element, index, array){ ... })
slides.forEach(function (slide, index) {
slide.style.left = `${index * 100}%`;
// console.log(slide);
// console.log(index);
// console.log(array);
});
let count = 0;
nextBtn.addEventListener("click", function () {
count++;
carousel();
});
prevBtn.addEventListener("click", function () {
count--;
carousel();
});
function carousel() {
slides.forEach(function (slide) {
if (count > slides.length - 1) {
count = 0;
}
if (count < 0) {
count = slides.length - 1;
}
slide.style.transform = `translateX(-${count * 100}%)`;
// console.log(slides.length);
// console.log(slide);
// console.log(count);
});
}
setInterval(()=>{
count++
carousel()
}, 3000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.