0

谁能帮我逐行理解这段代码

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); 是什么?意思是?

4

3 回答 3

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);
            });
}
于 2013-11-12T15:51:19.710 回答
0

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

于 2013-11-12T15:57:41.157 回答
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.

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

于 2013-11-12T16:00:48.183 回答