我有一个旋转木马问题,setInterval 和 style.transform = "translateX"

I have a problem with a carousel, setInterval and style.transform = "translateX"

我不明白为什么当函数必须显示计数器时它可以工作,如果我让她翻译一个元素她只翻译一次。

这是代码,我试了很多但找不到解决方案:

var i; //  set your counter to 1
var numberOfImages = document.getElementsByClassName("imgs").length;
var imgWidth = window.innerWidth;
    
console.log(numberOfImages);
    
var startIt = setInterval(function() {
    document.getElementById("carouselTrain").style.transform = "translateX(" + -imgWidth + "px)";
    document.getElementById("carouselTrain").style.transitionDuration = "0.5s";
    document.getElementById("carouselTrain").style.transform = "translateX(" + -imgWidth + "px)";
    document.getElementById("carouselTrain").style.transitionDuration = "0.5s";        
}, 1000);

问题是您每次都按相同的值进行翻译。翻译不会累积,这就是为什么您没有看到任何变化。

如果您在设置间隔函数中更新 imgWidth 的值,您将开始看到一些动作。在 setInterval 函数的底部执行此操作:

imgWidth += imgWidth