问题
I want to change an image every 3 seconds, but when changing I want to make a fade effect, to do so I was doing:
<script type="text/javascript">
var images = [];
images[0] = "http://i2.ytimg.com/vi/Q1yo3mco40U/default.jpg";
images[1] = "http://i2.ytimg.com/vi/ivmoCcYLrEk/default.jpg";
images[2] = "http://i3.ytimg.com/vi/f7d8luQ6p2Q/default.jpg";
images[3] = "http://i1.ytimg.com/vi/XzFmOKNf8sc/default.jpg";
images[4] = "http://i2.ytimg.com/vi/-2m1e4g2MFM/default.jpg";
images[5] = "http://i1.ytimg.com/vi/lK2TSYBh7fw/default.jpg";
var loop;
var i = 0;
$(document).ready(function() {
setTimeout(fadeDivs, 3000);
});
function fadeDivs()
{
$('.product img').attr('src',images[i]).fadeOut(100);
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
}
</script>
and:
<section id="product">
<article class="product">
<img src="http://i2.ytimg.com/vi/Q1yo3mco40U/default.jpg" />
</article>
</section>
However is not working, I think the problem is in
$('.product img').attr('src',images[i]).fadeOut(100);
Is there a better way to do this?
here is jsfiddle
回答1:
You need to use fadeIn()
and fadeOut()
along with the complete callbacks to do it
var images = [];
images[0] = "http://i2.ytimg.com/vi/Q1yo3mco40U/default.jpg";
images[1] = "http://i2.ytimg.com/vi/ivmoCcYLrEk/default.jpg";
images[2] = "http://i3.ytimg.com/vi/f7d8luQ6p2Q/default.jpg";
images[3] = "http://i1.ytimg.com/vi/XzFmOKNf8sc/default.jpg";
images[4] = "http://i2.ytimg.com/vi/-2m1e4g2MFM/default.jpg";
images[5] = "http://i1.ytimg.com/vi/lK2TSYBh7fw/default.jpg";
var i = 0;
setInterval(fadeDivs, 3000);
function fadeDivs() {
i = i < images.length ? i : 0;
$('.product img').fadeOut(100, function(){
$(this).attr('src', images[i]).fadeIn(100);
})
i++;
}
Demo: Fiddle
Note: In the fiddle, you missed to include jQuery
来源:https://stackoverflow.com/questions/18996053/fade-changing-image-every-n-seconds