jQuery:动画十进制数

时间:2015-09-21 15:41:11

标签: javascript jquery html css animation

我正在尝试动画从0到36.6的数字,但目前没有运气,因为它只是将最终值四舍五入到37,正如您在此处可以看到的那样:http://jsfiddle.net/neal_fletcher/0f3hxej8/
必要的标记如下:

HTML

<div id="el"></div>

jQuery的:

// Animate the element's value from x to y:
  $({someValue: 0}).animate({someValue: 36.6}, {
      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)));
      },
      complete:function(){
          $('#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;
  }

理想情况下,我希望它也可以通过小数生成动画,例如35.9,36.0,36.1,36.2等等。非常感谢任何建议!

2 个答案:

答案 0 :(得分:2)

您可以在舍入前乘以十舍入到小数点后一位,然后再除以十。

Math.round(this.someValue * 10) / 10)

如您更新的jsfiddle

所示

答案 1 :(得分:1)

一种解决方案是使用MDN上提供的Math.round10功能。您只需将代码更改为:

 $('#el').text(commaSeparateNumber(Math.round10(this.someValue, -1)));

<强> Updated Fiddle