jQuery 动画不会转到目标编号

jQuery animate wont go to target number

我想将百分比设为 100,但 jQuery 动画有时会停在 99!

JS代码:

count = 15;
total = 15;

var now = Math.ceil(( count / total ) * 100);
$('.Count').html('<strong>' +now + '</strong> ');
$({countNum: 0}).animate({countNum: now}, {
  duration: 1000,
  easing: 'linear',
  step: function () {
    $('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
  }
});

HTML:

COUNT: <span class="Count"></span><br />
PERCENTAGE: <span class="Percent"></span>

Jsfiddle:http://jsfiddle.net/MbRE9/464/

您必须尝试一下,看看它不会总是以 100% 结束。

当您的 animation 处于活动状态时,

step 仅 运行s,它不保证最后一步会 100% 发生。您需要在 animate()done 属性 中 运行 自定义函数,以确保动画完成时代码为 运行:

/*...*/.animate({/*...*/},{
  /*...*/,
  step: function(){
    $('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
  },
  done: function(){
    $('.Percent').html('<strong>' + Math.ceil(this.countNum) + '</strong> %');
  }
}

如果不想写两次,就放在一个变量中:

count = 15;
total = 15;

var now = Math.ceil(( count / total ) * 100),
    cNumUp = function(num) {
      $('.Percent').html('<strong>' + Math.ceil(num) + '</strong> %');
    };
$('.Count').html('<strong>' +now + '</strong> ');

$({countNum: 0}).animate({countNum: now}, {
  duration: 1000,
  easing: 'linear',
  step: function(){cNumUp(this.countNum)},
  done: function(){cNumUp(this.countNum)}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
COUNT: <span class="Count"></span><br />
PERCENTAGE: <span class="Percent"></span>

.animate() documentation

step

Type: Function( Number now, Tween tween ) A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set.

所以你可以使用像

这样的东西

count = 159;
total = 15;

var now = Math.ceil(( count / total ) * 100);
$('.Count').html('<strong>' +now + '</strong> ');
$({countNum: 0}).animate({countNum: now}, {
  duration: 1000,
  easing: 'linear',
  step: function (now_on_step) {      //<<<<<<< now_on_step here
    $('.Percent').html('<strong>' + Math.ceil(( now_on_step / now ) * 100) + '</strong> %');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
COUNT: <span class="Count"></span><br />
PERCENTAGE: <span class="Percent"></span>

无论您的 now 变量是什么,它总是 return 100%