Jquery淡入淡出旋转3个div
我试图在3个div之间淡出旋转,当前代码:
$(window).load(function(){ var div1 = $("#apDiv1"); var div2 = $("#apDiv2"); function fade() { div1.stop(true, true).fadeIn(2000); div2.stop(true, true).fadeOut(2000, function() { // swap in/out var temp = div1; div1 = div2; div2 = temp; // start over again setTimeout(fade, 1000); }); } // start the process fade(); })
这适用于2个div,但是可以在旋转中插入第3个吗?
我试过这样:
$(window).load(function(){ var div1 = $("#apDiv1"); var div2 = $("#apDiv2"); var div3 = $("#apDiv3"); function fade() { div1.stop(true, true).fadeIn(2000); div2.stop(true, true).fadeOut(2000); div3.stop(true, true).fadeIn(2000); div1.stop(true, true).fadeOut(2000, function() { // swap in/out var temp = div1 div1 = div2; div2 = div3; div3 = div1; div1 = temp // start over again setTimeout(fade, 1000); }); } // start the process fade(); })
但这只是跳过它/根本不起作用。
为了公平,如果你打算使用两个以上的div我会重写那个函数,所以它会做任何数量而不是只有三个div
我假设你的div看起来像这样(我给了他们一类fade
,起始的有一类current
)
给定此结构,您可以在window.load
使用以下jquery:
var divs = $('.fade'); function fade() { var current = $('.current'); var currentIndex = divs.index(current), nextIndex = currentIndex + 1; if (nextIndex >= divs.length) { nextIndex = 0; } var next = divs.eq(nextIndex); next.stop().fadeIn(2000, function() { $(this).addClass('current'); }); current.stop().fadeOut(2000, function() { $(this).removeClass('current'); setTimeout(fade, 2500); }); } fade();
例
修改代码将div1保存为temp变量。
var temp= div1; div1 = div2; div2 = div3; div3 = div1; div1 = temp;
谢谢,
湿婆
$(function(){ fade(); }); function fade() { div1.stop(true, true).fadeIn(2000, function(){ $(this).fadeOut(2000); div2.stop(true, true).fadeIn(2000, function(){ $(this).fadeOut(2000); div2.stop(true, true).fadeIn(2000, function(){ $(this).fadeOut(2000); setTimeout(fade, 2000); }); }); }); }
您可以使用fade()
函数并将其从doc准备好中移出,并在doc ready中调用它。
你错过了第一个div的变化:
jsFiddle: http : //jsfiddle.net/M4ddY/4/
我的建议(可在http://jsfiddle.net/skjHN/获得 ):
function rotateFade() { var toFadeOut = $('[id^=apDiv].current'); var toFadeIn = $('[id^=apDiv].current + [id^=apDiv]'); toFadeIn = toFadeIn.length ? toFadeIn : $('[id^=apDiv]:first-child'); toFadeOut.removeClass('current').fadeOut(2000); toFadeIn.addClass('current').fadeIn(2000); setTimeout(rotateFade, 1000); } // start the process rotateFade();