【问题标题】:Decimal Values Animation issue in JavascriptJavascript中的十进制值动画问题
【发布时间】:2018-03-08 15:15:53
【问题描述】:

我为数字创建了一个动画,当将其设置为较低的值(如 0.25 值)时,最后一位数字没有动画,我希望这个数字动画 0.19、0.20、0.21、0.22、0.23 以达到结果。

但是当我们将值提供为 20.9 时,它就是动画。谁能帮我解决这个问题。

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');
  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },
    {
      duration: 8000,
      easing: 'linear',
      step: function() {
        $this.text(Math.round(this.countNum * 10 / 10));
      },
      complete: function() {
        $this.text(this.countNum);
        //alert('finished');
      }
    });
});
body {
  background-color: #F46A6A;
  color: #fff;
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  display: table-cell;
  margin: 1.5%;
  font-size: 50px;
  background-color: #FF6F6F;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter" data-count="0.25">0</div>
<div class="counter" data-count="21.9">0</div>
<div class="counter" data-count="2200">0</div>

这是在线演示。 https://codepen.io/anon/pen/RMwPox

【问题讨论】:

  • 你认为 Math.round() 应该做什么?

标签: javascript jquery jquery-ui jquery-animate


【解决方案1】:

打开开发工具,选择控制台选项卡并输入:

Math.round(0.25);

查看该结果将证明您的代码完全按照您的要求执行。

您将需要使用.toFixed(2) 或其他一些解决方案来确保您考虑到两个小数。然后您需要对输出做出选择,因为所有三个都将显示 2 个小数位。

显示 21.9 起作用的原因是,当它向上取整到 22 时,动画 看起来 正确,因为最后你交换了最终结果 (22)实际输入 21.9 - 它们是如此接近以至于没有被注意到。

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多