javascript幻灯片的递归功能不起作用

时间:2016-09-09 13:04:14

标签: javascript recursion

我不知道为什么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>

我有3张HTML图片。

变量slideIndex最多为3并保持为3。

2 个答案:

答案 0 :(得分:1)

您不应该使用classList,因为它没有得到适当的支持:

&#13;
&#13;
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);
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

<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>