我每 5 秒更改一次 div 的背景图像以使其看起来不错我将图像添加到 div 作为 background
。我的脚本在图像转换之间添加了白色,这让它看起来很糟糕,我试图修复它但似乎没什么用。下面的代码片段现在显示使用 FadeIn 效果的图像,如果我向其添加 FadeOut,那么它会在过渡之间添加白色。
var imgSrcs = [
"../img/bg1.jpg",
"../img/bg2.jpg",
"../img/bg3.jpg",
"../img/bg4.jpg",
"../img/bg5.jpg"
];
var index = 1;
$('.intro').css("background-image", "url(" + imgSrcs[0] + ")")
$('.intro').fadeIn('slow', animateBackground());
function animateBackground() {
window.setTimeout(function () {
var url = imgSrcs[index];
index++;
if (index == 5)
index = 0;
$('.intro').delay(5000).fadeIn(1000, function () {
$(this).css("background-image", "url(" + url + ")")
}).fadeIn(1000, animateBackground())
});
}
我不确定如何解决这个问题,以便它可以在图像之间进行图像淡出和淡入
最佳答案
用这个
<script type="text/javascript">
$('#background_cycler').hide();//hide the background while the images load, ready to fade in later
</script>
<img class="active" src="images/img1.jpg" alt=""/>
<img src="images/img2.jpg" alt="" />
<img src="images/img3.jpg" alt="" />
<img src="images/img4.jpg" alt=""/>
<img src="images/img5.jpg" alt="" />
</div>
<style>
#background_cycler{padding:0;margin:0;width:100%;position:absolute;top:0;left:0;z-index:-1}
#background_cycler img{position:absolute;left:0;top:0;width:100%;z-index:1}
#background_cycler img.active{z-index:3}
</style>
<script>
function cycleImages() {
var $active = $('#background_cycler .active');
var $next = ($('#background_cycler .active').next().length > 0) ? $('#background_cycler .active').next() : $('#background_cycler img:first');
$next.css('z-index', 2);//move the next image up the pile
$active.fadeOut(1500, function () {//fade out the top image
$active.css('z-index', 1).show().removeClass('active');//reset the z-index and unhide the image
$next.css('z-index', 3).addClass('active');//make the next image the top one
});
}
$(window).load(function () {
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})
</script>
关于javascript - jQuery FadeIn 和 FadeOut 动画在中间显示白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29120790/