我已获得以下代码:
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>
&#13;
但是正如你所看到的那样,在for-for span中它显示了Price3。但是我希望它随着价格的上涨而循环上涨。 例如: 现在是37100,那么什么是Price1。 现在是40000,那么什么是Price2。 现在是100000然后是什么价格。
我做错了什么?
答案 0 :(得分: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>
答案 1 :(得分:0)
如果您愿意,可以在Rejith R Krishnan代码中为每个动画添加一个比率。
我将对象关联数组改为:
var prices = [
37152.32,
54023,
37261.75
];
和比率:
var ratios=[];
for(var i = 0; i < prices.length; i++){
ratios[i]=prices[i]/total;
}