循环javascript函数

时间:2013-09-25 14:08:23

标签: javascript

我有一个脚本可以创建一个进度条,并且是CSS的样式。它工作得很好,但是一旦栏到达终点,它就会停止,我无法让脚本循环以便它再次启动。如何循环此脚本,以便进度条一旦到达结束就重新开始?

<script type="text/javascript">
$(document).ready(function() {
var el = $(''#progress'');
el.animate({
width: "100%"
}, 40000);
});
</script>


<style>
#progressKeeper {background:#f2f2f2;display:none;width: 400px;height: 18px;border: 1px         solid #CCC;-moz-border-radius:7px; border-radius:7px;color:#f2f2f2;font-family:Arial;font-    weight:bold;font-style:italic;font-size:.9em;margin-bottom:2000px;}
#progress {background: #005c9e;width: 0;height: 17px;-moz-border-radius:7px; border-    radius:7px;}
</style>

2 个答案:

答案 0 :(得分:3)

删除jQuery,使用CSS3!

#progress {
    animation:progress 40s linear infinite;
    -webkit-animation:progress 40s linear infinite;
}

@keyframes progress {from {width:0} to {width:100%}}
@-webkit-keyframes progress {from {width:0} to {width:100%}}

如果你必须支持过时的浏览器......好吧,将回调传递给animate函数,告诉它再次启动动画。像这样:

$(function() {
    var prog = $("#progress");
    anim();
    function anim() {
        prog.css({width:0});
        prog.animate({width:"100%"},40000,anim);
    }
});

答案 1 :(得分:2)

使其成为一个函数,并将该函数作为完成处理程序传递给.animate调用。请参阅jQuery().animate()

类似的东西:

$(document).ready(function() {
    function animateProgressBar( ) {
        $('#progress').width(0).animate({
            width : "100%"
        }, 40000, animateProgressBar);
    }

    animateProgressBar();
});

(未测试的)