用setinterval创建jQuery动画

Art*_*ski 4 jquery

我的jQuery代码:

    $(document).ready(function(){
        setinterval(function(){
        $("#animate").animate({'margin-left':'50px'},1000)
        $("#animate").animate({'margin-left':'-50px'},1000)
        },2000); 

        });
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="animate">sdfdsfdsfsdfsdfds</div>
Run Code Online (Sandbox Code Playgroud)

我想做每5秒钟一次的动画.怎么了?谢谢 !

Bra*_*d M 10

我的首选解决方案 这样,您的动画将100%真正同步,并且不会受到重叠动画的影响.相信我,而其他答案使用setInterval(),它"看起来"像它的工作,由于javascript的异步性质,这些解决方案将在经过足够的迭代后莫名其妙地失败.此外,它只对元素进行一次 DOM查找,并使其成为jQuery对象一次.

jQuery(function($){
    (function swoop(element) {
        element
            .animate({'margin-left':'50px'}, 1000)
            .animate({'margin-left':'-50px'}, 1000, function(){
                setTimeout(function(){
                    swoop(element);
                }, 5000);
            });
    })($('#animate'));
});
Run Code Online (Sandbox Code Playgroud)