我想每隔3秒更换一次图片,但是在更改时我想要制作淡入淡出效果,我这样做了:
<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>
和
<section id="product">
<article class="product">
<img src="http://i2.ytimg.com/vi/Q1yo3mco40U/default.jpg" />
</article>
</section>
然而不起作用,我认为问题在于
$('.product img').attr('src',images[i]).fadeOut(100);
有更好的方法吗?
答案 0 :(得分:5)
您需要使用fadeIn()
和fadeOut()
以及完整的回调来执行此操作
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++;
}
演示:Fiddle
注意:在小提琴中,你错过了包含jQuery