简体   繁体   中英

Add Slidein Transition Effect for Image When img src Changes?

I'm having an img tag in .HTML file like below:

<img id="xyz"/>

In javascript, I have code like the below:

let i = 1;
let images = ["src1", "src2", "src3", "src4", "src5"];

let imgDiv = document.getElementById('xyz');
imgDiv.src = images[0];

setInterval(() => {
    momentDiv.src = images[i];
    i++;
    if(i == images.length) i=0;
}, 5000);

I image in imgDiv is switching every 5 seconds.

How to give animation or transition to the image whenever "src" property changes?

No jQuery please.

It's not possible to do it like you want.

To make a slide effect, you need at least 2 images. So you need to update the src of your second image and move this image above your first one. Then your second image should become first (the src of second image you need to copy to the old image tag and repeat the algorytm)

 let i = 1; let images = ["https://picsum.photos/200/200/?image=663", "https://picsum.photos/200/200/?image=662", "https://picsum.photos/200/200/?image=661", "https://picsum.photos/200/200/?image=660", "https://picsum.photos/200/200/?image=659"]; let imgDiv = document.getElementById('xyz'); let imgSecond = document.getElementById('zyx'); imgDiv.src = images[0]; setInterval(() => { imgSecond.src = images[i]; imgSecond.classList.add('active'); i++; if(i == images.length) i=0; setTimeout(function() { imgDiv.src = imgSecond.src; imgSecond.classList.remove('active'); }, 1500); // the same time as transition animation at css. }, 2000); 
 .wrap { position: relative; overflow: hidden; width: 200px; height: 200px; } .wrap > img { position: absolute; top: 0; left: 0; } .wrap > img#zyx { top: 200px; } .wrap > img#zyx.active { top: 0; transition: top 1.5s; } 
 <div class="wrap"> <img id="xyz" width="200" height="200"/> <img id="zyx" width="200" height="200"/> </div> 

Hope this helps you.

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