gpt4 book ai didi

javascript - 动画数字需要在 60 秒内停止

转载 作者:行者123 更新时间:2023-11-30 11:25:18 25 4
gpt4 key购买 nike

数字从开始(1,000)结束(10,000)。但我希望这个动画在某个预定义的时间内停止,比如 60 秒。 end value 可以很大,即 23,600,191 但此动画需要在 60 秒内停止。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

function myCalculator() {

$(".container2").show();
var start = 1000;
var end = 10000;
var duration = 2000;
animateValue("value", start, end, duration);
}
function animateValue(id, start, end, duration) {
var range = end - start;
var current = start;
var increment = end > start? 11 : -1;
var stepTime = Math.round(duration / range);
var obj = document.getElementById(id);
var timer = setInterval(function() {
current += increment;
obj.innerHTML = parseFloat(current).toLocaleString('en-US');
if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
obj.innerHTML = parseFloat(end).toLocaleString('en-US');
clearInterval(timer);
}
}, stepTime);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button name="submit" type="button" id="contact-submit" onclick="myCalculator();" >Click Here to See Animation</button>
<div style="display:none;" class="container2">Animating Amount $ <span id="value" ></span></div>

注意:

如果结束值很小,比如 1,000,那么这个动画需要在 60 秒内停止,如果结束值很大,比如 10,000,000,那么这个动画也需要在 60 秒内停止。请帮我解决一下?

最佳答案

您可以遵循的一个策略是动画开始时的时间戳,并检查经过了多少时间才停止。

function myCalculator() {

$(".container2").show();
var start = 1000;
var end = 200000;
var duration = 2000;
animateValue("value", start, end, duration);

}

function animateValue(id, start, end, duration) {
var range = end - start;
var current = start;
var increment = end > start? 11 : -1;
var stepTime = Math.round(duration / range);
var obj = document.getElementById(id);
//timestamp when animation starts
var startTime = performance.now();
var timer = setInterval(function() {
current += increment;
obj.innerHTML = parseFloat(current).toLocaleString('en-US');

// this instruction check if has passed 60 seconds
// (performance.now() - startTime)/1000 > 60 )
if ((increment > 0 && current >= end) || (increment < 0 && current <= end) || ((performance.now() - startTime)/1000 > 60 )) {
obj.innerHTML = parseFloat(end).toLocaleString('en-US');
clearInterval(timer);
}
}, stepTime);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button name="submit" type="button" id="contact-submit" onclick="myCalculator();" >Click Here to See Animation</button>
<div style="display:none;" class="container2">Animating Amount $ <span id="value" ></span></div>

这条指令检查已经过了多少时间:

(performance.now() - startTime)/1000 > 60

关于javascript - 动画数字需要在 60 秒内停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285955/

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