我有以下代码:
代码:
$(document).ready(function(){
var header = $('body');
var backgrounds = new Array(
'url(/1.jpg)'
, 'url(/2.jpg)'
, 'url(/1.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
});
我可以在上面的代码中添加什么,以便在背景图像之间实现“平滑”过渡。我不想使用插件。
谢谢:)
答案 0 :(得分:2)
你可以淡出它,改变背景并将它淡出来:
function nextBackground() {
current++;
current = current % backgrounds.length;
header.fadeOut(200, function(){
header.css('background-image', backgrounds[current]);
header.fadeIn(200);
})
}
答案 1 :(得分:1)
如果要对幻灯片进行交叉淡入淡出,可以将图像的副本放在顶部,然后在下一张幻灯片更改时将其淡出。
$(document).ready(function(){
var image = $('.wrap');
var fader = $('.fader');
var backgrounds = new Array(
'url(http://placehold.it/480&text=Slide+1)'
,'url(http://placehold.it/480&text=Slide+2)'
,'url(http://placehold.it/480&text=Slide+3)'
);
var current = 0;
function nextBackground() {
// Change the background image while
// creating a duplicate of image and
// fade it out
fader.css('background-image', backgrounds[current]).fadeOut(function() {
fader.css('background-image', '').show();
});
current++;
current = current % backgrounds.length;
image.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 2000);
image.css('background-image', backgrounds[0]);
});

.wrap, .fader {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-size: contain;
background-repeat: no-repeat;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="fader"></div>
</div>
&#13;