gpt4 book ai didi

javascript - 随着数字的增加,数字增量动画持续时间变慢

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:18 28 4
gpt4 key购买 nike

我这里有一个计数代码:

HTML:

<div id="value">700</div>
<div id="value2">1000</div>

JavaScript:

function animateValue(id, start, end, duration) {
var start= 0 ;
var end = parseInt(document.getElementById(id).textContent, 10);
var duration = 10000;
var range = end - start;
var current = start;
var increment = end > start? 1 : -1;
var stepTime = Math.abs(Math.floor(duration / range));
var obj = document.getElementById(id);
var timer = setInterval(function() {
current += increment;
obj.innerHTML = current;
if (current == end) {
clearInterval(timer);
}
}, stepTime);
}
animateValue("value2",0,0,0);
animateValue("value",0,0,0);

在此代码中,数字从 0 开始,持续 10000 毫秒结束。当它接近尾声时,如何将这个持续时间设置得比这个慢?

例如:

数字:0 到 100。

持续时间:50 毫秒到 10 毫秒。

最佳答案

使用一些缓动函数而不是以恒定速率递增。

但是请注意,您的总执行时间可能总是至少有些不准确,因为值的每次递增都需要一些执行时间,而使用此 setTimeout 时并未考虑在内方法。更高的值会加剧该问题。

//No easing
function constant (duration, range, current) {
return duration / range;
}

//Linear easing
function linear (duration, range, current) {
return ((duration * 2) / Math.pow(range, 2)) * current;
}

//Quadratic easing
function quadratic (duration, range, current) {
return ((duration * 3) / Math.pow(range, 3)) * Math.pow(current, 2);
}

function animateValue(id, start, duration, easing) {
var end = parseInt(document.getElementById(id).textContent, 10);
var range = end - start;
var current = start;
var increment = end > start? 1 : -1;
var obj = document.getElementById(id);
var startTime = new Date();
var offset = 1;
var remainderTime = 0;

var step = function() {
current += increment;
obj.innerHTML = current;

if (current != end) {
setTimeout(step, easing(duration, range, current));
}
else {
console.log('Easing: ', easing);
console.log('Elapsed time: ', new Date() - startTime)
console.log('');
}
};

setTimeout(step, easing(duration, range, start));
}

animateValue("value", 0, 10000, constant);
animateValue("value2", 0, 10000, linear);
animateValue("value3", 0, 10000, quadratic);
<div id="value">100</div>
<div id="value2">100</div>
<div id="value3">100</div>

关于javascript - 随着数字的增加,数字增量动画持续时间变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32741635/

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