简体   繁体   English

带有4张图像的JavaScript幻灯片

[英]JavaScript Slideshow with 4 images

I'm trying to create a simple slideshow.. something isn't quite right and I'm not sure what. 我正在尝试创建一个简单的幻灯片..不太正确,我不确定是什么。 For some reason the startSlideShow function is being called but not implementing the altering of the "position" variable... 由于某种原因,正在调用startSlideShow函数,但未实现对“ position”变量的更改...

 var timer = null; var position = 0; var images = document.querySelectorAll('.slide img'); for (let i = 0; i < images.length; i++) { images[i].src = 'dog' + i + '.jpg'; var button = document.getElementById('control'); button.onclick = run; function run() { if (timer == null) { //stopped or page has just loaded timer = setInterval(startSlideShow, 4000); } else { clearInterval(timer); //this stops animation timer = null; } }; function startSlideShow() { position++; images[i].style.left = position + 'px'; }; } 
 <div class="slideshow"> <div class="slide-container"> <div class="slide"> <img> </div> <div class="slide"> <img> </div> <div class="slide"> <img> </div> <div class="slide"> <img> </div> </div> </div> <button id="control">Stop/Start</button> 

The logic that you were following is reversed. 您遵循的逻辑是相反的。 The loop of images should start with pressing of button where event listener on click need to be attached. 图像循环应从按下按钮开始,其中需要附加单击事件监听器。 Therefore function that iterates need to enclose the loop. 因此,迭代的功能需要封闭循环。 Try following code it uses IE6 syntax with arrow functions. 请尝试以下代码,该代码使用带有箭头功能的IE6语法。 Let me know if you need IE5 one but I guess you may easily figure out how to transform it if you need. 让我知道您是否需要IE5,但我想您可能会很容易地弄清楚如何转换它(如果需要)。

I've just refactored solution in order to behave like slideshow one :) 我刚刚重构了解决方案,使其表现得像幻灯片一:)

Here is working JsFiddle: https://jsfiddle.net/0t00oax8/ 这是正在工作的JsFiddle: https ://jsfiddle.net/0t00oax8/

Please try following code 请尝试以下代码

    var timer = null; 
    var position = 0;
    var images = document.querySelectorAll('.slide img');

    const showNextPic = () => {
           images[ (position > 0) ? (position-1) : 0 ].style = "display:none";
          if( position >= images.length){
             position = 0;
           }

           let imgName =  'dog' + position + '.jpg'
          images[position].src = imgName;
          images[position].alt = imgName;
          images[position].style = "display:block"
          position++;

    }

       var button = document.getElementById('control');

         button.addEventListener('click', () => {
         if (timer == null) { //stopped or page has just loaded
              timer = setInterval(showNextPic, 2000);
         }else {
             clearInterval(timer); //this stops animation
             timer = null;
          }    
       }) ;

Hope this helps! 希望这可以帮助!

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

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