简体   繁体   中英

Can I run an event when image has loaded using setAttribute(“src”) and getAttribute(“data-src”)?

On my website, I have created a lightbox that shows an image until the actual image is loaded. This is my code for loading the image:

function showSlides(n) {
    var i;
    var slides = document.getElementsByClassName("slides");
    if (n > slides.length) {slideIndex = 1}
    if (n < 1) {slideIndex = slides.length}
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";}
        slides[slideIndex-1].style.display = "block";
        slides[slideIndex-1].setAttribute("src",slides[slideIndex-1].getAttribute("data-src"));
}
<img class="slides" src="img/global/lazyload/lazyload.gif" data-src="img/home/Material_1.png">

Essentially I replace the src with data-src. However, I wish to run a fade-in effect once the data-src has loaded using CSS. How would I go about implementing that? Is there an on complete, or on load "event" that I can use. Is it possible to do with the only javascript?

Right now, the src image quickly snaps to the size of the actual image for a brief moment and then replaces the data-src.

The event that you are after is the load event on the DOM element.

The easiest way to transition is to have one element fade into view on top of another element. The following example does it by placing the image on top of a background image and performing a CSS transition.

 let img = document.querySelector('img'); img.addEventListener('load', e => { if (img.src !== 'https://picsum.photos/200/300?placeholder') { img.classList.add('show'); } }); setTimeout(() => { img.setAttribute('src', img.getAttribute('data-src')); }, 500); 
 .container, .container img { width: 200px; height: 300px; } .fade-in { transition: 1s; opacity: 0; } .show { opacity: 1; } 
 <div class="container" style="background-image: url('https://picsum.photos/200/300?placeholder')"> <img class="fade-in" src="https://picsum.photos/200/300?placeholder" data-src="https://picsum.photos/200/300?actual" /> </div> 

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