Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - A way to fade in the background on load?

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

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

1 Reply

0 votes
by (71.8m points)

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,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...