CSS background-image slideshow

后端 未结 4 1645
时光说笑
时光说笑 2020-12-08 05:57

I am pretty new to CSS and HTML, but I am learning the ropes. Right now, I have a background image on my header section and I am trying to turn this into a slideshow with 3-

4条回答
  •  长情又很酷
    2020-12-08 06:43

    Based on the accepted answer for this question, here’s a jQuery-dependent version that creates a random image slideshow, uses CSS3 for the transition and gets the image paths via HTML5 data attribute.

    Demo: https://jsbin.com/luhawu/1

    Note: All images should be same dimensions for best results.

    JS:

    (function($) {
    
        'use strict';
    
        var $slides = $('[data-slides]');
        var images = $slides.data('slides');
        var count = images.length;
        var slideshow = function() {
            $slides
                .css('background-image', 'url("' + images[Math.floor(Math.random() * count)] + '")')
                .show(0, function() {
                    setTimeout(slideshow, 5000);
                });
        };
    
        slideshow();
    
    }(jQuery));
    

    Minified:

    !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,5e3)})};n()}(jQuery);
    

    CSS:

    [data-slides] {
        background-image: url(../../uploads/banner1.jpg); /* Default image. */
        background-repeat: no-repeat;
        background-position: center top;
        background-size: cover;
        transition: background-image 1s linear;
    }
    
    /* Use additional CSS to control the `height` of `[data-slides]`, like so: */
    
    .test { height: 220px; }
    @media all and (min-width: 48em) {
        .test { height: 320px; }
    }
    

    HTML

    I’ve also put the code in a public Gist.

提交回复
热议问题