一种在负载下淡入背景的方法?

我正在进行网站设计,我需要一种方法来淡化身体标签的背景图像,当它完全加载时(可能然后暂停500毫秒)。

如果你看到八月的网站设计,你会看到背景渐渐消失; 但是,这是通过Flash背景完成的。 有没有办法用jQuery或JavaScript做到这一点?


2010年9月19日更新:

所以对于那些来自Google的人来说(这是目前“负载背景淡出”的头号结果),我只是想为每个人制作一个更清晰的实现示例。

在页脚中的某个位置添加

(如果您不希望DOM混乱,也可以通过JavaScript附加此代码)。

风格如此 –

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

然后将其添加到JavaScript脚本文件中(需要jQuery):

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

这样就可以在DOM完成后1秒内淡化#backgroundfade元素(覆盖“实际背景”的框)。

我自己没有这样做,但它可能会奏效。

我猜,你可以设置背景图像,然后用一个黑色背景的大旧div来掩盖它。 然后使用此div的不透明度来创建淡入淡出效果。 这个黑色的div必须覆盖整个身体。

是的:

不要给身体一个背景图像。 然后准备一个具有淡化效果的动画GIF。 在Javascript中:

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

在jQuery中它会是

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

如果你不想做动画GIF技巧,但需要支持JPEG或PNG,那就太讨厌了。 你必须创建一个占位符

,将它放在正确的位置并使用不透明度。 您还必须检测背景图像何时加载,以便在慢速连接时不会出现愚蠢的跳跃。 一个非工作的例子:

 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"; 

干杯,

我看到这个链接,

http://fragged.org/dev/changing-and-fading-body-background-image.php

这个想法是:

将您的背景应用于分配了低z-index,绝对定位和背景的div(将其视为反向/反向模式)。 然后用透明的背景将你的内容制作成另一层。

您现在可以通过id引用底层并更改不透明度。

它需要的是一个背景图像的堆栈/数组,作为属性应用于图层…

我不确定是否有办法让背景图像淡入,但是你能做到的一种方法是使用带有负z-index的绝对定位图像。 然后,您可以使用jquery淡入图像。 如果您需要平铺或重复背景图像,这种方法可能会更棘手。

HTML:

     

jQuery:

 $(window).load(function() { $("#backgroundImage").fadeIn("slow"); }); 

为什么不使用现成的脚本: 这个在页面加载时使背景图像淡入。

它还使图像适合窗口的尺寸,但如果不需要,可以禁用此function。

我的解决方案

HTML:

  

CSS:

 #myImg{ opacity: 0; -moz-opacity: 0; -khtml-opacity: 0; filter: alpha(opacity=0); } 

JS:

 var img = document.getElementById('myImg'), steps = 30, appearTime = 1000; img.src = "/path/to/img.gif"; img.onload = function(){ for(i=0; i<=1; i+=(1/steps)){ setTimeout((function(x){ return function(){ img.style.opacity = x; img.style.MozOpacity = x; img.style.KhtmlOpacity = x; img.style.filter = "alpha(opacity=" + (x*100) + ")"; }; })(i), i*appearTime); }; };