javascript - jQuery:动画小数

标签 javascript jquery html css animation

我正在尝试为从 0 到 36.6 的数字设置动画,但目前运气不佳,因为它只是将最终值四舍五入为 37,如您在此处的 fiddle 中所见: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 等。如有任何建议,我们将不胜感激!

最佳答案

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

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

如您更新的 jsfiddle 所示.

关于javascript - jQuery:动画小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699321/

相关文章:

javascript - 如何在不破坏 jquery 动画的情况下使用@keyframes 实现平滑的页面转换

javascript - 如何隐藏容器中的 DIV 类以及同一容器中的另一个 div?使用 jQuery

javascript - 你能在 Canvas 上画出弧形图像吗?

javascript - 使用jquery更改 `option`中 `select`的文本

javascript - iFrame 中的 jquery 访问元素

javascript - 带有 ng-repeat 的 bootstrap-labels 之间没有间距

javascript - 如何将本地文本信息加载到 <div> 部分

Javascript 库或 jquery 插件,用于在移动 safari/ipad 中创建基于滑动的轮播

javascript - 使用按钮/jquery 更改表的 css 样式

javascript - 更改工具提示位置/箭头