我已经创建了一个将一个数字递增到另一个数字的函数。然而,我的持续时间逻辑不起作用。
.animateNumber()
中的第三个参数是持续时间,我希望这是增加到新数字所花费的时间。
因此,如果持续时间设置为500,那么它将从10(开始) - 500(结束)开始递增500毫秒,这对于任何起始值和结束值都是相同的。
http://jsbin.com/kepibetuxu/edit?html,js,console,output
HTMLElement.prototype.animateNumber = function(start, end, duration) {
this.style.opacity = 0.5;
var self = this,
range = end - start,
current = start,
increment = end > start? 1 : -1,
stepTime = duration / range,
timer = setInterval(function() {
current += increment;
self.innerHTML = current;
if (current == end) {
self.style.opacity = 1;
clearInterval(timer);
}
}, stepTime);
console.log(range);
console.log(stepTime);
};
document.querySelector('.value').animateNumber(400, 500, 20);
document.querySelector('.value1').animateNumber(0, 500, 20);

<div class="value">0</div>
<div class="value1">0</div>
&#13;
我如何修复我的stepTime逻辑来执行此操作?
答案 0 :(得分:3)
我只是请求新的帧,并在那时将数字更新为approapriate分数:
function animateNumber(el, start, end, duration) {
var startTime = performance.now();
(function func() {
var factor = Math.min(1, (performance.now() - startTime) / duration);
el.textContent = (start + (end-start) * factor).toFixed(0);
el.style.opacity = factor;
if(factor < 1) requestAnimationFrame(func);
})();
}
animateNumber(document.querySelector('.value1'), 400, 500, 2000);
animateNumber(document.querySelector('.value2'), 0, 500, 2000);
<div class="value1">0</div>
<div class="value2">0</div>
答案 1 :(得分:0)
这是你如何为你的功能添加刷新率:
HTMLElement.prototype.animateNumber = function(start, end, duration, refresh) {
this.style.opacity = 0.5;
var self = this,
refresh = refresh || 10,
range = end - start,
stepQt = duration/refresh | 0,
increment = end > start? range/stepQt : -range/stepQt ,
current = start;
var timer = setInterval(function() {
current += increment ;
if (current >= end) {
current = end;
self.style.opacity = 1;
clearInterval(timer);
}
self.innerHTML = current | 0;
}, refresh);
};
document.querySelector('.value').animateNumber(400, 500, 2000);
document.querySelector('.value1').animateNumber(0, 500, 2000, 10);
&#13;
<div class="value">0</div>
<div class="value1">0</div>
&#13;
刷新率可以帮助您了解增量应该基于动画中的步数,而不是基于逐个增量调整刷新率;
您也无法添加刷新率,因为我添加了默认值;