我如何在jQuery中做3个动画并循环它们? (时间搞定了。)

时间:2015-04-21 03:00:26

标签: javascript jquery loops fadein fadeout

我有三种不同的过渡效果,用于淡化和淡化我的3张图像。

animate1 = function() {
    $('#changingImage').fadeOut('fast', function() {
        $('#changingImage').attr("src","../files/others/image1.jpg");
        $('#changingImage').fadeIn('fast');
    });
};

我有两次相同的功能,只需用2s和3s替换1s。 我用这个调用我的三个函数,每5秒重复一次:

animate1().delay(5000);
animate2().delay(10000);
animate3().delay(15000);

我是jQuery的新手,我不明白时机错误的原因。所有发生的事情是image2(原始版本)被image1取代,而那就是它。

4 个答案:

答案 0 :(得分:1)

.delay()不会重复某个事件,只会延迟执行。如果您想根据给定的时间间隔重复某个事件,则需要.setInterval()

   window.setInterval(function(){
     setTimeout(animate1, 1000);
     setTimeout(animate2, 500);  
   }, 5000);

演示:https://jsfiddle.net/erkaner/bfb7jgaL/1/

答案 1 :(得分:1)

尝试使用setTimeout() javascript函数。

文档:http://www.w3schools.com/jsref/met_win_settimeout.asp

例如:

setTimeout(function(){ animate1(); }, 5000);
setTimeout(function(){ animate2(); }, 5000);
setTimeout(function(){ animate3(); }, 5000);

这会基本上“暂停”您的JavaScript / jQuery代码5秒钟,然后再运行该函数并继续。

答案 2 :(得分:1)

耶!我找到了一堆帮助。

var animations = function() {
    setTimeout(function() { 
        animate1();
        console.log("Animation 1")
    }, 5000);
    setTimeout(function() { 
        animate2();
        console.log("Animation 2")
    }, 10000);
    setTimeout(function() { 
        animate3();
        console.log("Animation 3")
    }, 15000);
};
setInterval(animations, 15000);

答案 3 :(得分:0)

您好我有一个建议,如果你有超过这个3图像所以你将为它创建一个新的功能? 那么只使用一个函数来调用它自带一个定义图像名称的属性,因为它是唯一一次改变,所以你可以使用这个更好更少的代码,你只需要n值每次都会改变会增加,最大值会定义你想要的图像数量



//if you want to set this animation for more than 3 image just change the max value
var max=3;
setTimeout(function(){ animate(2); }, 5000);
animate = function(n) {
$('#changingImage').fadeOut('fast', function() {
if(n<=max){
    $('#changingImage').attr("src","http://www.imacros-scripts-for-free.is-best.net/image"+n+".jpg");
    $('#changingImage').fadeIn('fast');
    if(n==max){n=1}else{n++;}
setTimeout(function(){ animate(n); }, 5000);
}
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="changingImage" src="http://www.imacros-scripts-for-free.is-best.net/image1.jpg" width="200px">
&#13;
&#13;
&#13;