2011-09-01 162 views
0

我正在使用一个简单的脚本来每隔X秒更改我的网站的背景图片。我想要做的是包含某种淡入淡出的动画或从一个图像到下一个图像的过渡。达到此目的的最佳方法是什么?褪色背景图片

我不是很擅长Javascript,所以请耐心等待。 :)

<script type="text/javascript"> 
    var images = ['bg1.png', 'bg2.png', 'bg3.png']; 
    var curImage = 0; 
    function switchImage() 
    { 
     curImage = (curImage + 1) % images.length 
     document.body.style.backgroundImage = 'url(images/' + images[curImage] + ')' 
    } 
    window.setInterval(switchImage, 5000); 
</script> 

我看了个遍和不明白请,请有人给我一个工作的代码,所以我可以复制和粘贴,摆脱这恼人的工作。 这里的例子http://preferredmerchantservices.net/

+0

其实......你应该使用jQuery。我知道......一个简单功能的大型图书馆,但基于个人经验,它不会是一个“简单”功能。另外,jQuery在后台处理所有跨浏览器兼容性,这非常好。 (哦,并且也很容易使用jQuery的转换方法)。 –

+0

尝试设置间隔的图像不透明度或使用Jquerry将更容易褪色。 –

回答

0

似乎没有人使用老式的js脚本来实现这样的动画了。我建议你使用jQuery或其他JavaScript库,它们基本上是浏览器JavaScript功能的抽象层。

此外,您还可以找到很多示例,插件等,以了解您所提到的过渡效果。

  1. 过渡效果的插件:http://malsup.com/jquery/cycle/
  2. jQuery的网站,这是很容易的,并采取了几天我学习吧:http:///www.jquery.com

希望它能帮助。

0
  • 做出同样尺寸的DIV为你的形象
  • 设置你的图像作为CSS背景
  • 把第二个“前景”的形象在你的DIV零不透明
  • 淡出第二图像
  • 交换的形象 - >使其成为DIV
  • 设置前景图像的不透明度的CSS背景零
  • 交换为n个前景图像转一个
  • 重复
0

万一你需要重写的jQuery的代码。这里有:

<script type="text/javascript"> 
    var images = ['bg1.png', 'bg2.png', 'bg3.png']; 
    var curImage = 0; 
    var timer; 
    function switchImage() { 
     $('body').css({'backgroundImage':'url(images/' + images[curImage] + ')'}; 
     curImage == images.length? curImage = 0; curImage++; 
     clearInterval(timer); 
     timer = setInterval(switchImage, 5000);   
    } 
    timer = setInterval(switchImage, 5000);   
</script> 

我想指出,这不会淡入/出背景图像,但是。要做到这一点,你可以使用一个容器作为背景图片。可能调整大小的东西。

// Resize Handler 
$(window).resize(function() { 
    resizePages(); 
}); 

function resizePages() { 

    var width = $(window).width(); 
    var height = $(window).height(); 

    $('.backgroundContainer').css({'width': width}); 

    /* 
     .contentWrapper would be where all your page's content is placed 
     .backgroundContainer is a class for a div placed out side teh contentWrapper 
     It would have a lower z-index than .contentWrapper but higher than body. 
    */ 


    /* 
     This makes sure that the background image is the same height as 
     either the windows of the .contentWrapper (whichever is larger) 
    */ 
    if (height > $('.contentWrapper').height()){ 
     $('.backgroundContainer').css({'height': height}); 
    } else { 
     $('.backgroundContainer').css({'height': $('.contentWrapper').height()}); 
    } 
} 

然后,您可以调整切换代码以淡入转场之间的背景。