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

时间:2012-02-25 08:05:04

标签: 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> 

5 个答案:

答案 0 :(得分:9)

查看浏览器控制台。 animatethis不会返回任何内容,这意味着该行

animatethis.stop();

总会崩溃(类似“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);

还有很多其他方法可以让这只猫受到伤害,但这确实有效。 http://jsfiddle.net/mattball/rKu6Y/

答案 1 :(得分: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);​

答案 2 :(得分:3)

尝试this小提琴

<强> HTML

<div class="myDiv">A Div</div>​

<强> JS

$('.myDiv').animate({
   'margin-left':'50px'
}, 500, function(e){
$('.myDiv').animate({
    'margin-left':'0px'
}, 500)});​

答案 3 :(得分:1)

如果你要多次来回移动它,你可以将它包装成一个自我调用的函数。像这样:

function wobble(selector, amount, times, intSpeed) {

    var string = String($(selector).css("marginLeft")).replace("px", ""),
    leftMargin = parseInt(string, 10);

    $(selector).animate({ marginLeft: (leftMargin + amount) + 'px' }, intSpeed, function () {
        if (times > 0) {
            wobble(selector, -amount, --times, intSpeed);
        } else {
            $(selector).css("marginLeft", leftMargin + 'px');
        }
    });
}

答案 4 :(得分:0)

使用jQuery queue()方法链接事件:http://api.jquery.com/queue/

相关问题