49

我正在通过间隔更新 anumeric value内部。elementajax requests

为了使整个事情更有活力,我想通过current在一段时间内部new分地减少或减少.valuen 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库?

4

10 回答 10

114

您可以非常简单地自己编写代码:

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>


这是一个更准确的版本,可以自我调整,以防计时器间隔不完全准确(有时不是):

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>

于 2013-06-08T00:19:15.620 回答
18

当前的解决方案确实比需要的更新频率更高。这是一种基于框架的方法,它是准确的:

function animateValue(obj, start, end, duration) {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.innerHTML = Math.floor(progress * (end - start) + start);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);
div {font-size: 50px;}
<div id="value">100</div>

于 2020-02-19T00:09:50.653 回答
6

我对这种动画的处理方式略有不同。基于这些假设:

  1. 有一个起始文本(作为非 JS 浏览器或谷歌索引的后备)
  2. 此文本可以包含非数字字符
  3. 该函数将元素直接作为第一个参数(而不是元素 ID)

因此,如果您想为“+300% 毛利率”之类的简单文本设置动画,则只会对数字部分进行动画处理。

start此外,所有参数现在都具有end和的默认值duration

https://codepen.io/lucamurante/pen/gZVymW

function animateValue(obj, start = 0, end = null, duration = 3000) {
    if (obj) {

        // save starting text for later (and as a fallback text if JS not running and/or google)
        var textStarting = obj.innerHTML;

        // remove non-numeric from starting text if not specified
        end = end || parseInt(textStarting.replace(/\D/g, ""));

        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));
            // replace numeric digits only in the original string
            obj.innerHTML = textStarting.replace(/([0-9]+)/g, value);
            if (value == end) {
                clearInterval(timer);
            }
        }

        timer = setInterval(run, stepTime);
        run();
    }
}

animateValue(document.getElementById('value'));
#value {
    font-size: 50px;
}
<div id="value">+300% gross margin</div>

于 2019-01-20T15:10:26.160 回答
6

现在我们可以使用 CSS 变量和新的@property为计数器(以及许多以前无法动画的东西)设置动画。不需要javascript。目前仅支持Chrome 和 Edge。

@property --n {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

body {
  display: flex;
}

.number {
  animation: animate var(--duration) forwards var(--timing, linear);
  counter-reset: num var(--n);
  font-weight: bold;
  font-size: 3rem;
  font-family: sans-serif;
  padding: 2rem;
}
.number::before {
  content: counter(num);
}

@keyframes animate {
  from {
    --n: var(--from);
  }
  to {
    --n: var(--to);
  }
}
<div class="number" style="--from: 0; --to: 100; --duration: 2s;"></div>
<div class="number" style="--from: 10; --to: 75; --duration: 5s; --timing: ease-in-out"></div>
<div class="number" style="--from: 100; --to: 0; --duration: 5s; --timing: ease"></div>

于 2021-03-26T22:35:54.507 回答
4

这很好用。但是,我需要在数字中使用逗号。下面是检查逗号的更新代码。希望有人偶然发现这篇文章时会发现这很有用。

function animateValue(id, start, end, duration) {

    // check for commas
    var isComma = /[0-9]+,[0-9]+/.test(end); 
    end = end.replace(/,/g, '');

    // 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);
        }
        // Preserve commas if input had commas
        if (isComma) {
            while (/(\d+)(\d{3})/.test(value.toString())) {
                value = value.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
            }
        }
    }

    var timer = setInterval(run, stepTime);
    run();
}

animateValue("value", 100, 25, 2000); 
于 2015-02-03T11:55:45.833 回答
3

const counters = document.querySelectorAll('.counters');

counters.forEach(counter => {
  let count = 0;
  const updateCounter = () => {
    const countTarget = parseInt(counter.getAttribute('data-counttarget'));
    count++;
    if (count < countTarget) {
      counter.innerHTML = count;
      setTimeout(updateCounter, 1);
    } else {
      counter.innerHTML = countTarget;
    }
  };
  updateCounter();
});
<p class="counters" data-counttarget="50"></p>
<p class="counters" data-counttarget="100"></p>
<p class="counters" data-counttarget="500"></p>
<p class="counters" data-counttarget="1000"></p>

于 2021-05-20T18:08:34.113 回答
1

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Count</title>
</head>
<body>
    <div id="value">1000</div>
</body>
</html>

JAVASCRIPT 片段

这是一个简单的 js 函数,将值从给定的起始编号递减到结束编号​​(对象原型)..

function getCounter(startCount,endcount,time,html){
objects = {
    //you can alternateif you want yo add till you reach the endcount
    startCount:startCount,
    endCount:endcount,
    timer:time
}
this.function = function(){
    let startTm  = objects.startCount,
        timer = objects.timer,
        endCount = objects.endCount;
        //if you want it to add a number just replace the -1 with +1
        /*and dont forget to change the values in the object prototype given a variable of counter*/
    let increament = startTm  < endCount ? 1:-1;
        timmer  = setInterval(function(){
                startTm  += increament;
                html.innerHTML = startTm ;
                if(startTm  == endCount){
                    clearInterval(timmer);
                }
            },timer);
   }
}
// input your startCount,endCount  the timer.....
let doc = document.getElementById('value');

let counter = new getCounter(1000,1,10,doc);
//calling the function in the object
counter.function();

查看此演示https://jsfiddle.net/NevilPaul2/LLk0bzvm/

于 2018-04-30T07:33:47.823 回答
0

我混合使用了所有这些来创建一个更新 BehaviorSubject 的函数。

function animateValue(subject, timerRef, startValue, endValue, duration){
  if (timerRef) {  clearInterval(timerRef); }
  const minInterval = 100;
  const valueRange = endValue - startValue;
  const startTime = new Date().getTime();
  const endTime = startTime + (duration * 1000);
  const interval = Math.max((endTime-startTime)/valueRange, minInterval);

  function run() {
    const now = new Date().getTime();
    const rangePercent = Math.min(1-((endTime-now)/(endTime-startTime)),1);
    const value = Math.round(rangePercent * valueRange+startValue);

    subject.next(value);
    if (rangePercent >= 1) {
      clearInterval(timerRef);
    }
  }

  timerRef = setInterval(run, interval);
  run();
}
于 2020-07-03T02:36:18.930 回答
0

这就是我想出的:

function animateVal(obj, start=0, end=100, steps=100, duration=500) {   
    start = parseFloat(start)
    end = parseFloat(end)

    let stepsize = (end - start) / steps
    let current = start
    var stepTime = Math.abs(Math.floor(duration / (end - start)));
    let stepspassed = 0
    let stepsneeded = (end - start) / stepsize

    let x = setInterval( () => {
            current += stepsize
            stepspassed++
            obj.innerHTML = Math.round(current * 1000) / 1000 
        if (stepspassed >= stepsneeded) {
            clearInterval(x)
        }
    }, stepTime)
}   

animateVal(document.getElementById("counter"), 0, 200, 300, 200)
于 2020-04-29T21:50:05.360 回答
0

这是一个版本,其中增量按某个定义的乘数 (mul) 增长。frameDelay 是每个增量的时间延迟。如果你有 camn 的值,这看起来会更好一些

function cAnimate(id, start, end, frameDelay = 100, mul = 1.2) {
    var obj = document.getElementById(id);
    var increment = 2;
    var current = start;
    var timer = setInterval(function() {
        current += increment;
        increment *= mul;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }

        obj.innerHTML = Math.floor(current).toLocaleString();

    }, frameDelay);
}

cAnimate("counter", 1, 260000, 50);
于 2020-06-01T00:22:55.437 回答