gpt4 book ai didi

javascript - jQuery animate 从关联数组中获取当前值

转载 作者:行者123 更新时间:2023-11-28 06:04:30 26 4
gpt4 key购买 nike

我有以下代码:

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 又如何。

我做错了什么?

最佳答案

您代码中的问题是它在循环内调用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>

关于javascript - jQuery animate 从关联数组中获取当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com