2017-01-18 90 views
-2

我想知道是否有可能在jQuery .aniamte()函數中重複相同的屬性。例如,如果我有一個綠色的方塊,並且我想將它移到右側,那麼再往下一次。我該怎麼做?我嘗試再次寫入第一個.animate()函數,但它不起作用。jQuery重複使用.animate()的屬性

$(document).ready(function(){ 
 
    $("div").animate({left: "100px"}, "slow"); 
 
    $("div").animate({top: "100px"}, "slow"); 
 
    $("div").animate({left: "100px"}, "slow"); 
 
});
div { 
 
    height: 60px; 
 
    width: 60px; 
 
    background-color: green; 
 
    position: relative; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div></div>

+1

jquery的動畫支持+ =和 - =。看起來像這對你有用。 –

回答

1

最簡單的方法是使用+=

$(document).ready(function(){ 
 
    $("div").animate({left: "+=100px"}, "slow"); 
 
    $("div").animate({top: "100px"}, "slow"); 
 
    $("div").animate({left: "+=100px"}, "slow"); 
 
});
div { 
 
    height: 60px; 
 
    width: 60px; 
 
    background-color: green; 
 
    position: relative; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div></div>

0

的div有已經left: "100px"第一animate()後,如果您要添加額外的100px應該在下一次迭代left: "+=100px"

你的意思是這樣的:

$(document).ready(function(){ 
 
    $("div").animate({left: "100px"}, "slow"); 
 
    $("div").animate({top: "100px"}, "slow"); 
 
    $("div").animate({left: "+=100px"}, "slow"); 
 
    $("div").animate({top: "+=100px"}, "slow"); 
 
});
div { 
 
    height: 60px; 
 
    width: 60px; 
 
    background-color: green; 
 
    position: relative; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div></div>

0

你方未進一步移動,因爲它已經是left: 100px 如果你想你方進一步移動,你需要添加更多x/y!

原諒環路如何簡陋不過是:

var x = 100; 
    var y = 100; 
    for(var x=100; x<500; x+=100){ 
    $('div').animate({left:x+"px"}, 'slow') 
      .animate({top:y+"px"}, 'slow'); 
    y+=100; 
    } 

jsfiddle

0

只需將它包裝在一個遞歸函數(jsfiddle):

function anim(){ 
 
\t $("div").animate({left: "100px"}, "slow") 
 
    \t \t .animate({top: "100px"}, "slow") 
 
    \t \t .animate({left: 0}, "slow") 
 
       .animate({top: 0 }, "slow", function(){ anim(); }); 
 
} 
 

 
anim();
div { 
 
    height: 60px; 
 
    width: 60px; 
 
    background-color: green; 
 
    position: relative; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div></div>