简体   繁体   中英

How do I make a simple fade effect on an image slider with javascript(only)?

I'm using the following code to run a slider. The function runs well. How do I make a simple fadein effect with js. No jQuery. Also setInterval waits 5 seconds before displaying the first image. How do I start with an image and then continue with the 5 second interval?

  var i = 0; var hello = function(){ if(i<image.length) {document.getElementById('fullscreenImage').src = image[i]; i+=1; } else i = 0; } setInterval(hello,5000); 
 #fullscreenImage { z-index: -999; width: 100%; height: 100%; position: fixed; top: 0; left: 0; background-size: cover; } 
 <img id="fullscreenImage"></img> 

You can do this by progressively adjusting the opacity style property of an image. Here's a simple example: declare some HTML structure, then wire the sliding behavior, using the makeSlider() function, passing an array containing the target images, as well as fading parameters.

HTML file example (whatever.html) :

<head>
  <style type="text/css">
    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 300px;
      visibility: hidden;
    }
    img:first-child {
      visibility: visible;
    }
  </style>
  <script type="text/javascript" src="slider.js"></script>
</head>

<body>
  <img src="1.jpg" alt="Alt 1" />
  <img src="2.jpg" alt="Alt 2" />
  <script type="text/javascript">
    var fadeInterval = 3000;
    var fadeStep = 20;
    setTimeout(function() {
      makeSlider([document.images[0], document.images[1]], fadeInterval, fadeStep); 
    }, fadeInterval);
  </script>
</body>

Javascript file (slider.js):

function makeSlider(pictures, fadeInterval, fadeStep) {
  var currentIndex = 0;

  function show() {
    var nextIndex = (currentIndex + 1) % pictures.length;
    var current = pictures[currentIndex];
    var next = pictures[nextIndex];
    fade(current, 1, -0.1, function() {
      current.style.visibility = "hidden";
      next.style.visibility = "visible";
      fade(next, 0, +0.1, function() {
        currentIndex = nextIndex;
        setTimeout(function() { show(); }, fadeInterval);
      });
    }); 
  }

  function fade(element, origin, step, continuation) {
    element.style.opacity = origin;
    setTimeout(function () {
      var nextOrigin = Math.round((origin + step) * 10) / 10;    
      if (nextOrigin >= 0 && nextOrigin <= 1) {
        fade(element, nextOrigin, step, continuation);
      } else {
        continuation();
      }
    }, fadeStep);
  }

  show();
}

HTH.

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