简体   繁体   中英

Javascript slideshow background with images in order

I have the following code to rotate through some images. I need the images to go in order rather than be random. What do i need to change the code to in order to make that happen?

<div class="test"
data-slides='[
    "images/video/images/IMG_0001.jpg",
    "images/video/images/IMG_0002.jpg",
    "images/video/images/IMG_0003.jpg",
    "images/video/images/IMG_0004.jpg",
    "images/video/images/IMG_0005.jpg",
    "images/video/images/IMG_0006.jpg",
    "images/video/images/IMG_0007.jpg",
    "images/video/images/IMG_0008.jpg",
    "images/video/images/IMG_0009.jpg"
]'></div>

<script>
! function(t) {
"use strict";
var a = t("[data-slides]"),
    s = a.data("slides"),
    e = s.length,
    n = function() {
        a.css("background-image", 'url("' + s[Math.floor(Math.random() * e)] +
            '")').show(0, function() {
            setTimeout(n, 3.33e+2)
        })
    };
n()
}(jQuery);
</script>

Quite simple

  • add a c counter variable and loop your images using s[c++%e]
  • instead of setTimeout use .delay(2e3).show(0, n)

 ;(function(t) { "use strict"; var a = t("[data-slides]"), s = a.data("slides"), e = s.length, c = 0, // Add a counter n = function() { a.css("background-image", 'url("' + s[c++%e] + '")').delay(2e3).show(0, n); }; n(); }(jQuery)); 
 [data-slides]{height:100vh;background: none 50%;background-size: cover;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test" data-slides='[ "//placehold.it/800x600/0bf?text=1", "//placehold.it/800x600/fb0?text=2", "//placehold.it/800x600/f0b?text=3" ]'></div> 

... or even simple r operating only over your array:

var a = t("[data-slides]"),
    s = a.data("slides"),
    n = function() {
      a.css("background-image", 'url("'+ s[0] +'")').delay(2000).show(0, n);
      s.push(s.shift());
    };
n();

You can create a variable to increment while less array .length

! function(t) {
"use strict";
var a = t("[data-slides]"),
    s = a.data("slides"),
    e = s.length,
    i = -1,
    n = function() {
        a.css("background-image", 'url("' + s[++i] +'")')
        .show(0, function() {
            if (i < e -1) {
              setTimeout(n, 3.33e+2)
            }
        })
    };
n()
}(jQuery);

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