Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a website design, and I need a way to fade in the background image of the body tag when it is completely done loading (perhaps then a pause of 500 ms).

If you see August's website design you will see the background fades in; however, this is done with a Flash background. Is there any way to do this with jQuery or JavaScript?


Update 9/19/2010:

So for those that are coming from Google (this is currently the number one result for "fade in background on load", I just thought I'd make a more clear implementation example for everyone.

Add a <div id="backgroundfade"></div> to your code somewhere in the footer (you can also append this via JavaScript if you don't want your DOM getting cluttered.

Style as such -

#backgroundfade {
  position: fixed;
  background: #FFF /* whatever color your background is */
  width: 100%;
  height: 100%;
  z-index: -2;
}

Then add this to your JavaScript scripting file (jQuery required):

$(document).ready(function() {
? ? $('#backgroundfade').fadeOut(1000);
});

This has the effect of fading the #backgroundfade element (the box "covering" your actual background) out in 1 second upon DOM completion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yep:

Don't give the body a background image. Then prepare an animated GIF with the fading effect. In Javascript:

document.onload = function () {
  window.setTimeout (function () {
    document.getElementsByTagName ("body")[0].style.backgroundImage = "url(/path/to/image.gif)";
  }, 500);
};

In jQuery it would be

$(function () {
  $('body').css ('backgroundImage', 'url(/path/...)');
});

If you don't want to do the animated GIF trick, but need support for JPEG or PNG, it get's nasty. You'll have to create a placeholder <div/>, position it to the right place and play with opacity. You also have to detect when the background image has loaded, so that you don't get silly jumps on slow connections. A non-working example:

var x = new Image();
x.onload = function () {
  /*
    create div here and set it's background image to
    the same value as 'src' in the next line.
    Then, set div.style.opacity = 0; (best, when the
    div is created) and let it fade in (with jQuery
    or window.setInterval).
  */ };
x.src = "/path/to/img.jpg";

Cheers,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...