【问题标题】:Carousel of sliding images not looping when the iteration is done?迭代完成时滑动图像的轮播不循环?
【发布时间】:2021-08-16 21:38:05
【问题描述】:

我在 youtube 上找到了图片轮播教程。我把它放在一个网站上,它运行良好,但现在我试图将它实施到另一个网站,它不会循环。在迭代结束时,图像会从网站上消失。据我所知,两个文件中的代码是相同的。这里有什么问题?

var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.lenght) {myIndex = 1}
    x[myIndex - 1].style.display = "block";
    setTimeout(carousel, 1000);
}
<section>
  <img class="mySlides" src="photo/banner.jpg" style="width:100%">
  <img class="mySlides" src="photo/banner2.jpg" style="width:100%">
  <img class="mySlides" src="photo/banner3.jpg" style="width:100%">
  <img class="mySlides" src="photo/banner4.jpg" style="width:100%">
  <img class="mySlides" src="photo/banner5.jpg" style="width:100%">
</section>

【问题讨论】:

  • 您应该首先更正x.lenght 错字,然后将重置索引更改为零,因为 Javascript 使用基于零的数组 - 所以1 指的是集合中的第二张图片,这解释了为什么第一张图片disappears

标签: javascript html image carousel slideshow


【解决方案1】:

假设这不是问题中的拼写错误,请更改

if (myIndex > x.lenght) {myIndex = 1}

if (myIndex > x.length) {myIndex = 1}

【讨论】:

    【解决方案2】:

    作为您在这里调用的命名函数的替代方法,您可以使用这样的匿名函数。

    我怀疑整个问题都围绕着这样一个事实,即您将索引重置为 1 而不是 0 - 因此第一张幻灯片 "disappears"

    /*
      As a self-executing anonymous function that
      calls setTimeout within a new anon function
      to run indefinitely.
    */
    const _DELAY=2.5;
    
    
    
    (function(time){
      // create an array from HTML elements in the slide carousel
      let col=Array.from( document.querySelectorAll('img.mySlides') );
      let i=0;
    
      (function(){
        setTimeout( arguments.callee, time * 1000 );
        
        // hide the other slides
        if( i >= col.length )i=0;
        col.forEach( n=>n.style.display='none' );
        
        // select next image
        let img=col[i];
            img.style.display='block';
            
        // to show the progress
        console.log(i,img.src)
        i++;
    
      })();
    })( _DELAY );
    <section>
      <img class="mySlides" src="photo/banner.jpg" style="width:100%">
      <img class="mySlides" src="photo/banner2.jpg" style="width:100%">
      <img class="mySlides" src="photo/banner3.jpg" style="width:100%">
      <img class="mySlides" src="photo/banner4.jpg" style="width:100%">
      <img class="mySlides" src="photo/banner5.jpg" style="width:100%">
    </section>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多