继续在javascript中播放动画

时间:2014-05-28 10:48:06

标签: javascript jquery html css

我想要实现一些like this(标题图片底部的淡化动画箭头,表示用户需要向下滚动)。 为此,我打算使用下面的代码。 问题是动画只播放1倍,而我希望它能连续播放(以不会占用太多资源的方式播放)。见http://jsfiddle.net/ZN3aD/

$('.icon').css('display', 'block');
$('.icon').animate({ opacity: 1 }, 0);
$('.icon').animate({ opacity: 0, top: "100px" }, 'slow');

4 个答案:

答案 0 :(得分:5)

我建议你使用CSS动画:

.icon {
    ...
    -webkit-animation: icon 1.2s infinite;
    animation: icon 1.2s infinite;
}

@-webkit-keyframes icon {
    from {
        opacity: 1;
        top: 80px;
    }
    to {
        opacity: 0;
        top: 100px;
    }
}
@keyframes icon {
    from {
        opacity: 1;
        top: 80px;
    }
    to {
        opacity: 0;
        top: 100px;
    }
}

它可以在IE10 +中使用。

演示:http://jsfiddle.net/ZN3aD/6/

如果你想要旧的浏览器支持,那么看看James Donnelly的回答。或者您可以使用此代码段:

(function animate() {
    $('.icon').animate({ opacity: 1, top: 80 }, 0)
    .animate({ opacity: 0, top: 100 }, 'slow', animate);
})();

演示:http://jsfiddle.net/ZN3aD/8/

答案 1 :(得分:4)

将其设置为递归函数,在动画完成时调用自身。 (JSFiddle demo)。

$('.icon').css('display', 'block');

function animate() {
    // jQuery's CSS method should be used instead of an instant animation
    $('.icon').css({ opacity: 1 });

    $('.icon').animate({
        opacity: 0,
        // jQuery handles the units for you, so you can just use a number here
        top: 100
    },'slow', function() {
        // I assume you want the top value to be reset here
        $(this).css({ top: 80 });

        // Call the animate() function again when the animation has completed
        animate();
    });
}

// Trigger the animation initially
animate();

答案 2 :(得分:0)

这是一个解决方案:

var arwtimer = 0;

$('.icon').css('display', 'block');
$('.icon').animate({ opacity: 1 }, 0);


function pleaseScroll() {
    $('.icon').css({ top: 80 }, 0).animate({ opacity: 1 }, 222);;

    $('.icon').delay(999).animate({ opacity: 0, top: "100px" }, 999);
}

arwtimer = setInterval(pleaseScroll, 4000);

http://jsfiddle.net/rvvb2/

答案 3 :(得分:-1)

这应该可以解决问题。添加setInterval将重复放置在函数内的动画:

     function runAnimation(){

     $('.icon').css('display', 'block');
     $('.icon').animate({ opacity: 1 }, 0);
     $('.icon').animate({ opacity: 0, top: "100px" }, 'slow');

                }

var interval = setInterval(runAnimation,1000);