我尝试使用javascipt创建一个简单的滑块。问题是当计数器到达最后一个元素时,它不会将显示更改为阻止 这是代码
<div id="slider">
<img class="slide" src="img/img13.jpg" alt=""/>
<img class="slide" src="img/img14.jpg" alt=""/>
<img class="slide" src="img/img15.jpg" alt=""/>
<img class="slide" src="img/img16.jpg" alt=""/>
<img class="slide" src="img/img17.jpg" alt=""/>
<img class="slide" src="img/img18.jpg" alt=""/>
</div>
var delay = 3000;
var i = 0;
var allSliderSlides = document.getElementsByClassName('slide');
allSliderSlides[0].style.display = "block";
setInterval(function(){
i++;
allSliderSlides[i].style.display = "block";
if(allSliderSlides[i-1].style.display=="block"){
allSliderSlides[i-1].style.display="none";
}
if(i == allSliderSlides.length-1){
i = 0;
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
}
},delay);
请给我一些建议或建议来解决这个问题 感谢
答案 0 :(得分:0)
您在最后一个要成为块的元素
之前重新分配了i = 0尝试:
if(i == allSliderSlides.length-1){
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
i = 0;
}
答案 1 :(得分:0)
问题在于:
if(i == allSliderSlides.length-1){
i = 0;
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
}
您在更改样式前重置计数器。这导致显示第一张图像,并且永远不会显示最后一张图像。
解决方案:将i = 0;
移动到块中的最后一行,如下所示:
if(i == allSliderSlides.length-1){
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
i = 0;
}
希望有所帮助。