How to fade loop gallery background images

前端 未结 1 1201
时光说笑
时光说笑 2020-12-13 16:55

I wish to rotate a background image of a div which I believe precludes me from using the excellant jQuery Cycle Plugin.

The code below is what I have so far but it d

相关标签:
1条回答
  • 2020-12-13 17:20

    Use-case jsBin Demo

    In order to Cross-fade a background image, you'll need an extra layer to overlay your gallery.
    Here's an example of the logic involved:

    So create a DIV an place into it normal <img> tags for the browser to pre-load images, we'll use their src afterwards to use as covered background-image for the two elements:

    jQuery(function($) {
    
      var $gallery = $("#gallery"); // Your HTML gallery
      var $overlay = $("<div/>");   // An overlay to X-fade
      var $images = $gallery.find("img");
      var n = $images.length; // How many images we have
      var c = 0; // Just a counter to loop using Reminder Operator %
    
      $gallery.css({backgroundImage: "url("+ $images[c].src +")"}).append( $overlay );
    
      (function loopBg(){
        $overlay.hide().css({backgroundImage: "url("+ $images[++c%n].src +")"}).delay(2000).fadeTo(1200, 1, function(){
          $gallery.css({backgroundImage: "url("+ $images[c%n].src +")"}); 
          loopBg();
        });
      }());
    
    });
    html, body{
      height:100%; margin:0; /*If needed*/ 
    } 
    
    
    #gallery,      /*Your gallery ID */
    #gallery > div /*Immediate DIV child, created by jQuery*/
    {
      position:absolute;
      width: 100%; height:100%;
      background: #000 none 50% / cover;
    }
    #gallery img{
      display:none;
      /*Exactly. We'll use them as BG images*/
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="gallery">
      <!--
    We'll not show images, those are just used for the browser to preload them
    Let's just steal the images Sources and use them for the #gallery and #overlay backgrounds
    -->
      <img src="http://dummyimage.com/600x365/fc5/fff&text=Image1" />
      <img src="http://dummyimage.com/600x365/cf5/fff&text=Image2" />
      <img src="http://dummyimage.com/600x365/f5c/fff&text=Image3" />
    </div>

    0 讨论(0)
提交回复
热议问题