jQuery Fade在3 div之间旋转 [英] Jquery fade rotate between 3 divs

查看:34
本文介绍了jQuery Fade在3 div之间旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试淡入淡出3格之间旋转,当前代码:

I'm trying to fade rotate between 3 divs, current code:

$(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格效果很好,但是是否可以在旋转中插入第3个格?

This works great with 2 divs, but is it possible to insert a 3rd one into the rotation ?

我尝试过这样:

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

但这只是跳过/根本不起作用.

But that just skips it / doesn't work at all.

推荐答案

为了公平起见,如果您要使用两个以上的div,我将重写该函数,以便它将执行任意数量的操作,而不仅仅是三个div

To be fair if you are going to use more than two divs I would rewrite that function so it will do any amount rather than just three divs

我假设您的div看起来像这样(我给了他们一个fade类,开始的那个类具有current)

I have assumed that your divs look something like this (I have given them a class of fade with the starting one having a class of current)

<div id="apDiv1" class="fade current"></div>
<div id="apDiv2" class="fade"></div>
<div id="apDiv3" class="fade"></div>

鉴于这种结构,您可以在window.load中使用以下jquery:

given this structure you can use the following jquery within your window.load:

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();

示例

这篇关于jQuery Fade在3 div之间旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆