简体   繁体   English

jQuery淡入淡出

[英]Jquery Fade in Fade out

I have the following code: 我有以下代码:

Code: 码:

$(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]);
});

What can I add to the above code so there is a "smooth" transition between background images. 我可以在上面的代码中添加些什么,以便在背景图像之间实现“平滑”过渡。 I prefer not to use a plugin. 我宁愿不使用插件。

THANKS :) 谢谢 :)

You can fade it out, change the background and fade it back in: 您可以淡出,更改背景,然后淡入:

function nextBackground() {
  current++;
  current = current % backgrounds.length;
  header.fadeOut(200, function(){
    header.css('background-image', backgrounds[current]);
    header.fadeIn(200);
  })
}

If you want to crossfade the slides, you can place a duplicate of the image on top and fade it out as the next slide changes underneath. 如果要交叉淡化幻灯片,可以将图像的副本放在顶部,然后随着下一张幻灯片的变化而淡出。

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM