2016-05-03 36 views
1

我有下面的代碼獲取當前值:jQuery的動畫從相關陣列

var tot = 0; 
 
var prices = { 
 
    "Price1:": 37152.32, 
 
    "Price2:": 54023, 
 
    "Price3:": 37261.75 
 
}; 
 
var animationDuration = 2000; // Must be lower than carousel rotation 
 

 
function animatePrices() { 
 
    var dur = animationDuration/Object.keys(prices).length; 
 
    for (var key in prices) { 
 
    tot += prices[key]; 
 

 
    $({ 
 
     p: 0 
 
    }).animate({ 
 
     p: tot 
 
    }, { 
 
     duration: dur, 
 
     easing: 'linear', 
 
     step: function(now) { 
 
     document.getElementById("total").textContent = now.toFixed(2); 
 
     document.getElementById("what-for").textContent = key + " $" + prices[key]; 
 
     } 
 
    }); 
 
    } 
 
} 
 

 
window.onload = function() { 
 
    animatePrices(); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
$<span id="total"></span> 
 
<br> 
 
<span id="what-for"></span>

但正如你所看到的,在無論什麼樣的跨度它顯示Price3。但是我希望它隨着價格的上漲而循環通過價格。 例如: 當現在是37100時,那麼什麼是Price1。 當現在是40000那麼什麼是Price2。 當現在是100000,那麼什麼是Price3。

我在做什麼錯?

+0

其中是'now'變量? –

+0

功能(現在)你的意思是? – MrDikke

回答

0

您代碼中的問題在於它在迴路中調用animate。這弄亂了你的變量邏輯。你可以使用像下面這樣的東西。我在這裏使用動畫的遞歸調用。

var tot = 0; 
 
var prices = { 
 
    "Price1:": 37152.32, 
 
    "Price2:": 54023, 
 
    "Price3:": 37261.75 
 
}; 
 
var pricesArray = Object.keys(prices); 
 
var animationDuration = 20000; // Must be lower than carousel rotation 
 
var dur = animationDuration/pricesArray.length; 
 
function animatePrices() { 
 
    key = pricesArray.shift(); 
 
    start = tot; 
 
    tot += prices[key]; 
 
    if(!key) 
 
    return false; 
 
    $({ 
 
    p: start 
 
    }).animate({ 
 
    p: tot 
 
    }, { 
 
    duration: dur, 
 
    easing: 'linear', 
 
    step: function(now) { 
 
     $("#total").text(now.toFixed(2)); 
 
     $("#what-for").text(key + " $" + prices[key]); 
 
    }, 
 
    done: animatePrices 
 
    }); 
 
} 
 

 
window.onload = animatePrices;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
$<span id="total"></span> 
 
<br> 
 
<span id="what-for"></span>

+0

看來,計數器重新啓動時,改變了什麼改變。 – MrDikke

+0

@MrDikke我已經更新了代碼。請檢查。 – RRK

0

如果願意,添加的比例爲在Rejithř克里希南代碼每個動畫。

我雖然改變了對象相關聯的陣列中,給:

var prices = [ 
    37152.32, 
    54023, 
    37261.75 
]; 

和比率:

var ratios=[]; 
for(var i = 0; i < prices.length; i++){ 
    ratios[i]=prices[i]/total; 
} 

https://jsfiddle.net/a6k9w9k7/