使用setTimeOut循环和动画

时间:2013-11-12 15:48:36

标签: jquery

任何人都可以帮我逐行理解这段代码吗

var $elements = $('#One, #Two, #Three, #Four');
function anim_loop(index) {
    $elements.eq(index).fadeIn(1000, function() {
        var $self = $(this);
        setTimeout(function() {
            $self.fadeOut(1000);
            anim_loop((index + 1) % $elements.length);
        }, 3000);
    });
}
anim_loop(0); // start with the first element

完整示例http://jsfiddle.net/w5YHY/

具体来说,我有这些问题:

为什么在这里使用setTimeOut?
var $ self = $(this);怎么办?
anim_loop是什么((index + 1)%$ elements.length);意思?

3 个答案:

答案 0 :(得分:1)

函数anim_loop以递归方式调用,并将在$elements中按索引加载元素。同时,当前显示的元素将淡出。

function anim_loop(index) {//function takes an integer index
    $elements.eq(index)//get the element at index
             .fadeIn(1000, function() {//fade in element over 1000ms and call passed function when done fading in
                var $self = $(this); //wrap current element with jQuery so we can use helpers
                setTimeout(function() {//create a timeout when the current element is being displayed
                    $self.fadeOut(1000);//hide current element
                    var nextIndex = (index + 1) % $elements.length; //next index in $elements (currentIndex add 1 mod length)
                    anim_loop(nextIndex);//load next element
                }, 3000);
            });
}

答案 1 :(得分:0)

获取index位置的元素。 “fadeIn()”表示您要在'1000' miliseconds (1 second)中显示该元素。方法内部的块代码将在'1000' miliseconds之后执行。所以你有第一个。变量self,它是您循环的元素。其次,你有一个'setTimeOut()'方法,这意味着它内部的块代码将在'3000' miliseconds之后运行。然后,'self.fadeOut(1000)'将隐藏当前元素,然后代码将再次调用该方法以使用下一个元素。

答案 2 :(得分:0)

为什么在这里使用setTimeOut? => SettimeOut is used to make sure the element is displayed for only 3 sec's (3000), after 3sec's hide the element and get the next element in line.

var $ self = $(this);做? It get's reference to the member on which the current function is invoked.

anim_loop是什么((index + 1)%$ elements.length);意思?

This means: whatever the current index is + 1 = next element, Now if index is the last element currently it needs to get back to zero hence it's doing a modulus with the length which get's you back to the first element.

模数的工作方式是只返回余数。