创建显示/隐藏连续循环所需的简单jQuery脚本




据我所知,我研究了这个论坛上的问题,但没有完全得到答案
我是jQuery方面的新手
我有这个div

<div id="main">
    <div id="1" class="trip">Item1</div>
    <div id="2" class="trip">Item2</div>
    <div id="3" class="trip">Item3></div>
</div>

我想依次在每个div中淡入,然后在下一个div中隐藏并淡入。
我希望这能在div中连续循环,直到访问者离开页面
我需要一步一步的帮助来实现这一目标
我是stackoverflow的新手,但我学得很快,所以请耐心等待:(

非常感谢您的帮助
//Ot_Gu

创建一个函数并将其用作fadeOut的回调,当元素淡出时将调用该函数。

var $elem = $('#main .trip'), l = $elem.length, i = 0;
function comeOn() {
    $elem.eq(i % l).fadeIn(700, function() {
        $elem.eq(i % l).fadeOut(700, comeOn);
        i++;
    });
}

http://jsfiddle.net/MtmxN/

这是我的小提琴

function name_of_the_function() {
    $('.trip').each(function (index) { //for each element with class 'trip'
        $(this).delay(index * 1000).animate({ //delay 1000 ms which is the duration of the animation
            opacity: 1 //animate the opacity from 0 to 1
        }, {
            duration: 1000, //duration
            complete: function () { //when the animation is finished
                $(this).css({
                    opacity: 0 //turn the opacity from 1 to 0 without animation
                });
                if (index == 2) { //if the index == 2 which means we are in the last element in this case as we have 3 elements (0,1,2)
                    name_of_the_function(); //go back to the function
                }
            }
        });
    });
}
name_of_the_function(); //call the function at first

以及我使用的css:

.trip {
    opacity:0;
    background:red;
    height:100px;
    width:100px;
}

以下是如何使用递归和元素ID列表来实现更灵活的解决方案。

var ids = ["#1","#2","#3"],
    time = 1000;

function cycleShowHide (i,ids,time) {
    if (i>=ids.length) {
        i = 0;
    }
    //hide previous
    if (i==0) {
        $(ids[ids.length-1]).hide(time);
    } else {
        $(ids[i-1]).hide(time);
    }
    //show next and repeat
    $(ids[i]).show(time, function(){
        i++;
        cycleShowHide(i);
    }
}
cycleShowHide(0,ids,time);

您可以使用jquery切换

<div id="main" style='display:none'>
     <div id="1" class="trip">Item1</div>
     <div id="2" class="trip">Item2</div>
     <div id="3" class="trip">Item3></div> 
</div>
<button id='mb'>Chick here</button>

写入脚本标记。。

 $("#mb").click(function(){
     $('#main').toggle();
 });

最新更新