javascript – 数字增加动画持续时间随着数字增加而变慢

我在这里有一个计数代码:

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.

持续时间:50ms至10ms.

解决方法:

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

但是,请注意,由于每个值的增量需要一些执行时间(使用此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>
上一篇:17 JQuery高级----学习笔记


下一篇:JQuery Animate()