简体   繁体   中英

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

 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. Let me know if you need IE5 one but I guess you may easily figure out how to transform it if you need.

I've just refactored solution in order to behave like slideshow one :)

Here is working 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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