如何在jQuery中重复函数调用 [英] How to repeat a function call in jQuery

查看:65
本文介绍了如何在jQuery中重复函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() { 
        function loop(){
            $('#picOne').fadeIn(0).fadeOut(8000);
            $('#picTwo').delay(2000).fadeIn(6000).fadeOut(5000);
            $('#picTree').delay(10000).fadeIn(2000).fadeOut(16000);
            $('#picFour').delay(12000).fadeIn(16000).fadeOut(5000);
        }
        loop();
    });
</script>

但是当最后一张图片淡出时,代码不会重复。有什么问题?

But when the last pic fades out, the code doesn't repeat. What is the problem?

推荐答案

假设您希望每个元素的动画持续时间相同:

Assuming you want to duration of the animation being the same for each element:

var $elements = $('#picOne, #picTwo, #picTree, #picFour');

function anim_loop(index) {
    // Get the element with that index and do the animation
    $elements.eq(index).fadeIn(1000).delay(3000).fadeOut(1000, function() { 
        // Kind of recursive call, increasing the index and keeping in the
        // the range of valid indexes
        anim_loop((index + 1) % $elements.length);
    });
}

anim_loop(0); // start with the first element

我不知道动画应该是怎样的,但是我希望它能让这个概念变得清晰。

I don't know exactly how the animation should be, but I hope it makes the concept clear.

更新:要在一段时间后同时淡出图像,请使用 setTimeout 并在回调中调用 fadeOut anim_loop

Update: To simultaneously fade out and in an image after a certain time period, use setTimeout and call fadeOut and anim_loop in the callback:

$elements.eq(index).fadeIn(1000, function() {
    var $self = $(this);
    setTimeout(function() {
        $self.fadeOut(1000);
        anim_loop((index + 1) % $elements.length);
    }, 3000);
});

DEMO

这篇关于如何在jQuery中重复函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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