【问题标题】:How to increment number using animate with comma using jQuery?如何使用 jQuery 使用带有逗号的动画来增加数字?
【发布时间】:2013-04-20 02:54:44
【问题描述】:

我正在尝试增加页面元素内的数字。但我需要在数字中包含一个逗号作为千位值。 (例如 45,000 而不是 45000)

<script>
// Animate the element's value from x to y:
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $('#el').text(Math.round(this.someValue));
      }
  });
</script>
<div id="el"></div>

如何使用带逗号的动画来增加数字?

【问题讨论】:

标签: jquery jquery-animate increment comma easing


【解决方案1】:

工作演示 http://jsfiddle.net/4v2wK/

随意更改它以满足您的需要,您也可以查看货币格式化程序,希望这能满足您的需要:)

代码

// Animate the element's value from x to y:
  var $el = $("#el"); //[make sure this is a unique variable name]
  $({someValue: 40000}).animate({someValue: 45000}, {
      duration: 3000,
      easing:'swing', // can be anything
      step: function() { // called on every step
          // Update the element's text with rounded-up value:
          $el.text(commaSeparateNumber(Math.round(this.someValue)));
      }
  });

 function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
  }

**输出*

【讨论】:

  • 知道为什么数字不一样吗?我正在输出周围的圆圈。
  • 嗨@AdrianFlorescu 嗯你是什么意思,抱歉不知道你在问什么? :) 你的意思是为什么不输出例如:44,444?像这样:jsfiddle.net/hVpqD
  • @Tats_innit 完全一样,但看起来这是因为动画步骤。我用原始值替换了完整值。完成:函数(){ where.text(endNr); } jsfiddle.net/5yBt8/10
  • 您还应该像这样添加一个完整的函数:step:function(){ //.. }, complete:function(){ $el.text(commaSeparateNumber(Math.round(this.someValue) ))); }
【解决方案2】:

你还应该像这样添加一个完整的函数:

step:function(){
    //..
},
complete:function(){
    $el.text(commaSeparateNumber(Math.round(this.someValue)));
}

更新小提琴:Demo

【讨论】:

  • 为什么?我相当肯定 step 函数即使在最后一个动画步骤中也会被调用。 complete 函数用于附加回调以在所有步骤完成后运行。
  • 有时最后的结果不是很好,最后是随机的,有时是 45000,有时是 4995 等等,所以我添加了这个功能,现在它工作得很好。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多