how to create an Automatic Slideshow in JS with manual control

时间:2019-04-08 13:21:54

标签: javascript html css

i currently have a working slideshow that can be controlled manually using previous and next buttons, i do however wish to apply an automatic cycle through the slideshow every 4 seconds while at the same time allowing for the user to continue manually change the slides.

    <!-- Slideshow container -->
    <div class="slideshow-container">

      <!-- Full-width images with number and caption text -->
      <div class="mySlides fade">
        <div class="numbertext">1 / 4</div>
        <img src="Images/AMDCPUAD.jpg" style="width:100%">
        <div class="text">Caption Text</div>
      </div>

      <div class="mySlides fade">
        <div class="numbertext">2 / 4</div>
        <img src="Images/cpuAD.jpg" style="width:100%">
        <div class="text">Caption Two</div>
      </div>

      <div class="mySlides fade">
        <div class="numbertext">3 / 4</div>
        <img src="Images/CASEAD.jpg" style="width:100%">
        <div class="text">Caption Three</div>
      </div>

         <div class="mySlides fade">
        <div class="numbertext">4 / 4</div>
        <img src="Images/MOTHERBOARDAD.jpg" style="width:100%">
        <div class="text">Caption Three</div>
      </div>

      <!-- Next and previous buttons -->
      <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
      <a class="next" onclick="plusSlides(1)">&#10095;</a>
    </div>
    <br>

    <!-- The dots/circles -->
    <div style="text-align:center">
        <div class="dot" onclick="currentSlide(1)"></div>
        <div class="dot" onclick="currentSlide(2)"></div>
        <div class="dot" onclick="currentSlide(3)"></div>
        <div class="dot" onclick="currentSlide(4)"></div> 
    </div>


    ///////////////////////////////////////////////// JavaScript

    var slideIndex = 1;
    showSlides(slideIndex);

    // Next/previous controls
    function plusSlides(n) {
      showSlides(slideIndex += n)
        }





// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1} 
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block"; 
  dots[slideIndex-1].className += " active"; 
}

thanks in advance for answers, i'm almost certain the solution is simple i just can't figure it out, despite my best efforts googling

2 个答案:

答案 0 :(得分:0)

You could try (not mine, but looks nice) this one: JS-Fiddle

        (function (name, context, definition) {
        if (typeof define === 'function' && define.amd) {
            define(definition);
        }
        else if (typeof module !== 'undefined' && module.exports) {
            module.exports = definition();
        }
        else {
            context[name] = definition();
        }
    })('Slideshow', this, function () {

        /**
         * Slideshow
         * @constructor
         * @param {HTMLElement} element
         */
        function Slideshow(element) {
            this.target = element;
            this.runner = element.children[0];
            this.frames = element.children[0].children;

            if (!this.current) {
                this._init();
            }
        }

        /**
         * Init
         * @private
         */
        Slideshow.prototype._init = function () {
            var self = this;

            this.current = 0;
            this.maximum = this.frames.length - 1;

            // Add next and previous buttons
            this.btnNext = document.createElement('button');
            this.btnPrev = document.createElement('button');
            this.btnNext.type = this.btnPrev.type = 'button';
            this.btnNext.className = 'next';
            this.btnPrev.className = 'prev';
            this.btnNext.innerHTML = 'Next slide';
            this.btnPrev.innerHTML = 'Previous slide';

            this.btnNext.onclick = function () {
                self.to(self.current + 1);
            };

            this.btnPrev.onclick = function () {
                self.to(self.current - 1);
            };

            this.target.appendChild(this.btnNext);
            this.target.appendChild(this.btnPrev);

            this.keyupHandler = function (e) {
                switch (e.keyCode) {
                    case 37:
                        self.to(self.current - 1);
                        break;
                    case 39:
                        self.to(self.current + 1);
                        break;
                }
            };

            if (this.target.addEventListener) {
                this.target.addEventListener('keyup', this.keyupHandler, true);
            }
            else {
                this.target.attachEvent('onkeyup', this.keyupHandler);
            }

            this.to(this.current);
        };

        /**
         * Loop
         * @private
         * @param {Number} x
         */
        Slideshow.prototype._loop = function (x) {
            if (x > this.maximum) {
                x = 0;
            }
            else if (x < 0) {
                x = this.maximum;
            }

            return x;
        };

        /**
         * To
         * @param {Number} x
         */
        Slideshow.prototype.to = function (x) {
            x = this._loop(x);

            if (this.frames[x]) {
                this.before = this._loop(x - 1);
                this.current = x;
                this.after = this._loop(x + 1);

                this._update();
            }
        };

        /**
         * Update
         * @private
         */
        Slideshow.prototype._update = function () {
            var classBefore = ' is-before ';
            var classCurrent = ' is-current ';
            var classAfter = ' is-after ';
            var classRegex = /is\-before|is\-current|is\-after/g;

            for (var i = 0, len = this.frames.length; i < len; i++) {
                this.frames[i].className = this.frames[i].className.replace(classRegex,
                    '');
            }

            this.frames[this.before].className += classBefore;
            this.frames[this.current].className += classCurrent;
            this.frames[this.after].className += classAfter;
        };

        /**
         * Teardown
         */
        Slideshow.prototype.teardown = function () {
            this.target.removeChild(this.btnNext);
            this.target.removeChild(this.btnPrev);

            if (this.target.removeEventListener) {
                this.target.removeEventListener('keyup', this.keyupHandler, true);
            }
            else {
                this.target.detachEvent('onkeyup', this.keyupHandler);
            }

            delete this.after;
            delete this.before;
            delete this.current;
            delete this.btnNext;
            delete this.btnPrev;
        };

        return Slideshow;

    });

    /* Init */
    var slideshows = document.querySelectorAll('[data-directive=slideshow]');

    for (var i = 0, len = slideshows.length; i < len; i++) {
        new Slideshow(slideshows[i]);
    }

答案 1 :(得分:0)

我已经弄清楚了,在这种情况下,我只是创建了一个称为“ autoSlide”的函数,并在脚本开始处设置了4000ms的间隔,然后每4秒执行一次此脚本并通过应用plusSlides( 1)每次执行时,将其加到“ currentslide”索引中。

    var slideIndex = 1;
showSlides(slideIndex);
setInterval(autoSlide,4000);
// Next/previous controls
function plusSlides(n) {

  showSlides(slideIndex += n)

    }


function autoSlide (n) {
    console.log("changeSlidePlease");
    plusSlides(1);
}



// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1} 
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block"; 
  dots[slideIndex-1].className += " active"; 

}