简体   繁体   中英

Adding transition effect on my image slider

So, i've made a simple image slider which works/looks like this:

var image = document.getElementById("img");
var images = ["images/img1.png", "images/img2.png", "images/img3.png"];

function imageSlider(counter) {
   var total = images.length - 1;
   imageCount = imageCount + counter;

   if (imageCount > total) {
      imageCount = 0;
   }
   if (imageCount < 0) {
      imageCount = total;
   }

   image.src = images[imageCount];
}

   var timed = window.setInterval(function () {
       imageSlider(1);
}, 2000);

Basically, its just changing the src of the image element on my html page every 2 second.

Is it possible to add a transition effect to the images every time they swap? Messed around a bit with transition/opacity with a css class, but didn't get it to work. So hopefully i could get some help with it here.

Also, i'm not using jquery.

You can only fade out to nothing, and then fade in a new image unless you plan adding another image element which will be behind the main one until the main one has faded out completely.

Here's an example with a single image element using CSS transition:

 var image = document.getElementById("img"); var images = ["http://www.mariogame.info/images/icon-facebook.png", "http://icons.iconarchive.com/icons/ph03nyx/super-mario/128/Mushroom-Super-icon.png"]; var imageCount = 2; function imageSlider(counter) { var total = images.length - 1; imageCount = imageCount + counter; if (imageCount > total) { imageCount = 0; } if (imageCount < 0) { imageCount = total; } image.className = "out" setTimeout(function(){ image.src = images[imageCount]; image.className = ""; }, 500); } var timed = window.setInterval(function () { imageSlider(1); }, 2000); 
 img {transition: opacity 0.5s linear; opacity: 1; height: 100px;} .out {opacity: 0;} 
 <img id="img" src="http://icons.iconarchive.com/icons/ph03nyx/super-mario/128/Mushroom-Super-icon.png" /> 

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