简体   繁体   English

javascript幻灯片的递归函数不起作用

[英]javascript slideshow's recursive function not working

I don't know why the if statement doesn't work.我不知道为什么 if 语句不起作用。

    <script>
    var slideIndex = 0;
function slideShow(){
    var images= document.getElementsByClassName('slider-box')[0].getElementsByTagName('img');

    images[slideIndex].classList.remove('show-slide');
    if(slideIndex > images.length-1)
        slideIndex = 0;

    slideIndex++;
    images[slideIndex].classList.add('show-slide');

    setInterval(slideShow,2000);
}
      slideShow();
</script>

I have 3 images in HTML .我有 3 张 HTML 图像。

The variable slideIndex goes up to 3 and stays at 3.变量 slideIndex 上升到 3 并保持在 3。

You shouldn't use classList as it isn't properly supported:您不应该使用classList,因为它没有得到正确支持:

 var slider = document.getElementById("slider"); var sliderIndex = 0; function slide() { for (var i = 0; i < slider.children.length; i++) { var cls = slider.children[i].getAttribute("class").replace(/.show/ig, ''); slider.children[i].setAttribute("class", cls); } slider.children[sliderIndex].setAttribute( "class", slider.children[sliderIndex].getAttribute("class") + " show" ); sliderIndex++; if (sliderIndex > slider.children.length - 1) { sliderIndex = 0; } } slide(); setInterval(slide, 3000);
 #slider {} #slider .slide { position: absolute; -moz-transition: all 1s linear 0s; -o-transition: all 1s linear 0s; -webkit-transition: all 1s linear 0s; transition: all 1s linear 0s; opacity: 0 !important; filter: alpha(opacity=0) !important; } #slider .slide.show { opacity: 1 !important; filter: alpha(opacity=100) !important; }
 <div id="slider"> <img class="slide" src="http://placehold.it/310x150/E8117F/000000?text=1" /> <img class="slide" src="http://placehold.it/310x150/7812E5/000000?text=2" /> <img class="slide" src="http://placehold.it/310x150/128AE5/000000?text=3" /> <img class="slide" src="http://placehold.it/310x150/12E594/000000?text=4" /> <img class="slide" src="http://placehold.it/310x150/E5B412/000000?text=5" /> </div>

try this:尝试这个:

<script>
var slideIndex = 0;
function slideShow(){
    var images= document.getElementsByClassName('slider-box')[0].getElementsByTagName('img');

    images[slideIndex].classList.remove('show-slide');

    slideIndex++;
    if(slideIndex > images.length) slideIndex = 0;
    images[slideIndex].classList.add('show-slide');

    setInterval(slideShow,2000);
}
slideShow();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM