【问题标题】:plain javascript - increment number using function like $.animate with comma普通的 javascript - 使用像 $.animate 和逗号这样的函数来增加数字
【发布时间】:2014-07-27 15:22:56
【问题描述】:

我正在开发一款游戏,该游戏将动画添加或减去的钱。

jquery的解决方案在这里:

How to increment number using animate with comma using jQuery?

如何在纯 javascript 中做到这一点?

我想避免使用 jquery

【问题讨论】:

  • 那不是动画……只是文字内容更新得非常快。

标签: javascript


【解决方案1】:

在这个解决方案中,不需要 jQuery

var from=40000, to=50000;
function increment() {
    setTimeout(function() {
        from++;
        if(from <= to) {
            document.getElementById("test").innerHTML = from;
            increment();
        }
    }, 10);
}
increment();

请访问 jsfiddle。 http://jsfiddle.net/TTaA4/

【讨论】:

    【解决方案2】:
        var counter = 0;
    
        var timer = setInterval(function () {
            if (counter >= 100 ) {
                clearInterval(timer);
            }
    
            counter++;
            // call numberWithCommas(counter) to get no.s with comma..
        }, 100);
    
    function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    

    上面的逗号函数代码是从https://stackoverflow.com/a/2901298/2466168无耻复制过来的

    【讨论】:

      【解决方案3】:

      http://jsfiddle.net/2MwSv/

      在您的 javascript 控制台中尝试一下:

      var a = 40000;
      var b = 45000;
      console.log(commaSeparateNumber(a));
      
      function animate(opts) {
      
          var start = new Date;
      
          var id = setInterval(function () {
              var timePassed = new Date - start
              var progress = timePassed / opts.duration
      
              if (progress > 1) progress = 1
      
              var delta = progress;
              opts.step(delta)
      
              if (progress == 1) {
                  clearInterval(id)
              }
          }, opts.delay || 10)
      
      }
      
      function commaSeparateNumber(val) {
          while (/(\d+)(\d{3})/.test(val.toString())) {
              val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
          }
          return val;
      }
      
      
      animate({
          delay: 10,
          duration: 3000,
          step: function (progress) {
              var difference = b - a;
              console.log(commaSeparateNumber(a + Math.round(progress * difference)));
          }
      });
      

      来源:

      http://javascript.info/tutorial/animation

      How to increment number using animate with comma using jQuery?

      【讨论】:

        猜你喜欢
        • 2013-04-20
        • 2020-01-16
        • 2012-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        • 1970-01-01
        相关资源
        最近更新 更多