2013-05-06 88 views
0

我试着在jQuery和CSS中做淡入淡出的背景,这是我的代码 - 但它不工作。有任何想法吗?jquery中的背景图像淡入淡出

var images = ['bg.jpg', '_4.jpg', '_5.jpg', '_6.jpg']; 
var i = 0; 

setInterval(function(){ 
$('body').animate({opacity: 0}, 'slow', function() { 
     $(this) 
      .css('background-image', function() { 
     if (i >= images.length) { 
      i=0; 
     } 
     return 'url(' + images[i++] + ')'; 
    }); 
      .animate({opacity: 1}); 
    }); 
}, 1000); 
}); 
+0

你意识到你不能真正动画背景图像不透明度,但只有元素本身。 – adeneo 2013-05-06 21:43:15

+0

[用jQuery淡化背景图片]可能的重复(http://stackoverflow.com/questions/1690869/fading-in-background-image-with-jquery) – Blazemonger 2013-05-06 21:43:30

回答

0

您可以为背景颜色设置动画,但不是背景图像,我也把头撞过这个墙。

见这里 - Fade in new background images on scroll

正如在回答我的问题,你需要使用<img>的具有负的z-index和褪色那些英寸

这是我如何做它 -

CSS

#img1, #img2, #img3, #img4 { 
    width:100%; 
    height:100%; 
    display:none; 
    position:fixed; 
    z-index:-1; 
} 

jQuery的

$(document).scroll(function() { 
    var y = $(this).scrollTop(); 
    if (y > 150) { 
     $('#img2').fadeIn(); 
    } 
    else {$('#img2').fadeOut('fast')}; 

    if (y > 300) { 
     $('#img3').fadeIn(); 
    } 
    else {$('#img3').fadeOut('fast')}; 

    if (y > 450) { 
     $('#img4').fadeIn(); 
    } 
    else {$('#img4').fadeOut('fast')}; 
}); 
0
setInterval(function(){ 
      $('.light').animate({opacity: 0}, 4000, function() { 
       $('.light').css({background:'url(./images/' + images[i++] + ') no-repeat top center'}).animate({opacity: 1},4000); 
       if (i >= images.length) { i=0; } 
      }); 
     }, 4000); 

这一项必须工作我尝试这对格