从A到B计数动画 [英] Count animation from number A to B
本文介绍了从A到B计数动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过间隔执行ajax requests
来更新element
内部的numeric value
.
I am updating a numeric value
inside an element
by doing intervalled ajax requests
.
为了使整个过程更加生动活泼,我想从current
值到new
一个值,通过在一段时间内部分 -in-或减小 n sec
.
To make the whole thing a bit more alive, I want to count from the current
value to the new
one, by partially in- or decreasing the value
over a time of n sec
.
基本上就是这样:
<div id="value">100</div>
<script type="text/javascript">
/** Decrease $value (over a time of 2 seconds) till it reaches 25 */
$value.increaseAnimation(-75, {duration:2});
</script>
是否有一个用于执行此操作的javascript库?
推荐答案
您可以自己简单地编写代码:
You can just code it yourself pretty simply:
function animateValue(id, start, end, duration) {
if (start === end) return;
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("value", 100, 25, 5000);
#value {
font-size: 50px;
}
<div id="value">100</div>
这是一个更准确的版本,可以在计时器间隔不太精确(有时有时不是)的情况下自我调整:
Here's is a more accurate version that self adjusts in case the timer intervals aren't perfectly accurate (which they sometimes aren't):
function animateValue(id, start, end, duration) {
// assumes integer values for start and end
var obj = document.getElementById(id);
var range = end - start;
// no timer shorter than 50ms (not really visible any way)
var minTimer = 50;
// calc step time to show all interediate values
var stepTime = Math.abs(Math.floor(duration / range));
// never go below minTimer
stepTime = Math.max(stepTime, minTimer);
// get current time and calculate desired end time
var startTime = new Date().getTime();
var endTime = startTime + duration;
var timer;
function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = value;
if (value == end) {
clearInterval(timer);
}
}
timer = setInterval(run, stepTime);
run();
}
animateValue("value", 100, 25, 5000);
#value {
font-size: 50px;
}
<div id="value">100</div>
这篇关于从A到B计数动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文