开发者

jquery fade in effect for background image

开发者 https://www.devze.com 2023-04-01 20:00 出处:网络
I have this markup for the background image: <img src=\"bg.jpg\" id=\"bg\" alt=\"\"> and this css:

I have this markup for the background image:

<img src="bg.jpg" id="bg" alt="">

and this css:

#bg { position: fixed; top: 0; left: 0; }
#bg {display:none;}

a开发者_开发百科nd this jquery:

$(document).ready(function(){
$('#bg').load(function() {
$(this).fadeIn('slow');
});
}); 

Basically it works, but the strange situation is that sometimes the image loads, sometimes not, sometimes I have to refresh the page few times. Take a look here to see what I'm talking about.


The thing is that the image loads before the script. So, by the time you are binding an eventhandler for the image load event, the image is already loaded and the event is not triggered.
You should execute your function when the window loads, not when the document is ready :

$(window).load(function(){
    $('#bg').load(function() {
       $(this).fadeIn('slow');
    });
}); 


The $(document).ready() event is fired when the DOM is ready, but BEFORE any images are guaranteed to have loaded.

So what you're experiencing MAY be, that sometimes you image just hasn't loaded when the .ready event fires.

Try using the .load event instead.


The whole point of .ready() is that your code will fire once "the DOM hierarchy has been fully constructed". Since you're waiting on an image, this would be exactly what you don't want. jQuery.load() "does not get triggered until all assets such as images have been completely received", so move your .load statement out of doc ready.

0

精彩评论

暂无评论...
验证码 换一张
取 消