2012-02-25 89 views
8

我想在某個區域內水平來回擺動div。我現在面臨的問題是,我無法弄清楚如何讓我的div在向前移動後移回來。如何使用jquery的動畫方法使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> 
+0

你想讓它循環,對不對? – 2012-02-25 08:17:44

+0

你只需要在第一次動畫後回調,試試我的答案。 – 2012-02-25 08:17:48

+0

是的,我希望它可以對不起,如果我沒有說清楚 – user798774 2012-02-25 22:05:45

回答

7

看着你的瀏覽器控制檯。 animatethis不返回任何東西,這意味着該行

animatethis.stop(); 

總是要崩潰(喜歡的事「類型錯誤:無法調用未定義的方法‘一站式’」)。您還在混合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/

+0

哇謝謝,這正是我需要和當我使用時是停止它打印的東西到輸出面板 – user798774 2012-02-25 23:21:22

+0

我想知道爲什麼它不會觸發堆棧溢出異常,因爲這本質上是一個無限遞歸。 – Neolisk 2016-07-13 15:14:09

+1

@Neolisk回調不會添加到堆棧 - 它們會在稍後調用。 – 2016-07-13 16:20:03

0

使用jQuery queue()方法來一連串的事件:http://api.jquery.com/queue/

+0

梅。沒有幫助。 -1 – 2012-02-25 08:18:43

+0

後面你會看重它:) – yoda 2012-02-25 08:19:45

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);​ 
+1

這是最好的。 – aleXela 2013-08-22 08:02:15

3

嘗試this小提琴

HTML

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

JS

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

我認爲OP想讓動畫循環。也許我錯了。 – 2012-02-25 08:19:08

+0

謝謝,但我認爲他只是想繼續前進,然後再回來。 – 2012-02-25 08:24:11

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'); 
     } 
    }); 
}