문제

How to detect if an image is loaded beforehand, then perform a callback animation to fade in the image?

I've 10 images scatter all over my website, I've simplified the html below for example:

<header>
    <img src="headerImage.jpg" />
</header>
<div class="content">
    <img src="contentImage.jpg" />
</div>
<footer>
    <img src="mylogo.jpg" />
    copyright 2014 mywebsite.com
</footer>

In my css I have set all my images opacity to 0 by default:

<style>
    img{opacity:0;}
</style>

To fade in the images I used:

$("img").animate({'opacity':1 },600);

Now the problem I'm facing is all images will fade in regardless of whether it is loaded or not in one go. Is there a way to detect individual image after it is loaded, then only fade in/trigger the animation callback?

도움이 되었습니까?

해결책

You can use load event

The load event is sent to an element when it and all sub-elements have been completely loaded.

Code

$('img').load(function(){
    $(this).animate({'opacity':1 },600);
});

DEMO

As soon as the image has been loaded, the handler is called.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top