我想在滑块中进行自动播放,但是遇到问题。显示下一个div后,不会继续显示另一个div。
我该如何解决?
这是我的代码:
<div class="container">
<div class="mySlides active" style="background-image: url('images/1.jpg')">
</div>
<div class="mySlides" style="background-image: url('images/2.jpg');">
</div>
<div class="mySlides" style="background-image: url('images/3.jpg');">
</div>
</div>
<script>
var currentSlide = 1;
var isPlaying = true;
function nextSlide() {
showSlide(currentSlide += 1)
}
function showSlide() {
var slides = document.getElementsByClassName("mySlides");
if (currentSlide > slides.length) {
currentSlide = 1;
}
for (i = 1; i < slides.length; i++) {
slides[i].style.opacity = "0";
}
slides[currentSlide-1].style.opacity = "1";
slides[currentSlide-1].style.transition = "all .5s";
// slides[slideIndex-1].setAttribute("style", "opacity: 1; transition: ease .5s;");
}
if (isPlaying) {
setTimeout(nextSlide, 1000);
}
</script>
答案 0 :(得分:0)
我已经稍微修改了您提供的代码。这是工作示例:
HTML
<div class="container">
<div class="mySlides" style="background-image: url('images/1.jpg')">1
</div>
<div class="mySlides" style="background-image: url('images/2.jpg');">2
</div>
<div class="mySlides" style="background-image: url('images/3.jpg');">3
</div>
Javascript:
var currentSlide = 1;
var isPlaying = true;
function nextSlide() {
showSlide(currentSlide += 1)
}
function showSlide() {
var slides = document.getElementsByClassName("mySlides");
if (currentSlide >= slides.length) {
currentSlide = 0;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.opacity = "0";
slides[i].style.display = "none";
}
slides[currentSlide].style.display = "block";
slides[currentSlide].style.opacity = "1";
slides[currentSlide].style.transition = "all .5s";
// slides[slideIndex-1].setAttribute("style", "opacity: 1; transition: ease .5s;");
}
if (isPlaying) {
setInterval(nextSlide, 500);
}