如何使用jquery的animate方法来使div来回移动

use*_*774 10 jquery jquery-animate

我想在某个区域内来回水平制作div动画.我现在面临的问题是,我无法弄清楚如何让我的div在向前移动之后向前移动.

这是我正在使用的脚本:

  <script type="text/javascript">
    var animatethis = function (targetElement, speed) {
        $(targetElement).animate(
            {
                marginLeft: "+=250px"
            },
            {
                duration: speed,
                complete: function () {
                    animatethis(this, speed);
                    animatethis.stop();
                    $(targetElement).animate({ marginLeft: "-=250px" });
                }
            }
                    )
    };
    animatethis($('#q1'), 5000);
</script> 
Run Code Online (Sandbox Code Playgroud)

Mat*_*all 9

查看浏览器控制台.animatethis不返回任何东西,这意味着该行

animatethis.stop();
Run Code Online (Sandbox Code Playgroud)

总会崩溃(类似"TypeError:无法调用未定义的方法'停止'").你也在混淆complete回调中动画的顺序.

停下来,呼吸,思考上面的代码实际上在做什么.


好的,所以在marginLeft增加之后,你想减少它.然后你想从头开始.对?所以:

function animatethis(targetElement, speed) {
    $(targetElement).animate({ marginLeft: "+=250px"},
    {
        duration: speed,
        complete: function ()
        {
            targetElement.animate({ marginLeft: "-=250px" },
            {
                duration: speed,
                complete: function ()
                {
                    animatethis(targetElement, speed);
                }
            });
        }
    });
};

animatethis($('#q1'), 5000);
Run Code Online (Sandbox Code Playgroud)

还有很多其他方法可以让这只猫皮肤,但这确实有效.http://jsfiddle.net/mattball/rKu6Y/

  • @Neolisk回调不会继续添加到堆栈 - 它们稍后会被调用. (2认同)

Che*_*ery 7

你想这样做吗?http://jsfiddle.net/vwH6R/2/

setInterval(function(){
    $("div").stop(true,true).animate({left: 300}, 1000, 
          function(){ $(this).stop(true,true).animate({left: 0}, 1000); 
    });
}, 2000);?
Run Code Online (Sandbox Code Playgroud)