jQuery动画数字计数器从零到百分比值

时间:2018-03-16 08:55:08

标签: jquery html timer counter animator

我正在处理项目,我想在结果页面中添加jQuery动画数字计数器从零到百分比值 - Javascript动画,数据库中的值是动态的吗?



function timer() {
  if (animator.curPercentage < animator.targetPercentage) {
    animator.curPercentage += 1;
  } else if (animator.curPercentage > animator.targetPercentage) {
    animator.curPercentage -= 1;
  }

  $(animator.outputSelector).text(animator.curPercentage + "%");

  if (animator.curPercentage != animator.targetPercentage) {
    setTimeout(timer, animator.animationSpeed)
  }
}

function PercentageAnimator() {
  this.animationSpeed = 50;
  this.curPercentage = 0;
  this.targetPercentage = 0;
  this.outputSelector = ".countPercentage";

  this.animate = function(percentage) {
    this.targetPercentage = percentage;
    setTimeout(timer, this.animationSpeed);
  }
}

var animator = new PercentageAnimator();
animator.curPercentage = 40;
animator.animate(70);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="countPercentage">98%</span>
<span class="countPercentage">92%</span>
<span class="countPercentage">12%</span>
<span class="countPercentage">67%</span>
&#13;
&#13;
&#13;

问题是jQuery函数PercentageAnimator正在运行,但只到70?

如何在countPercentage而不是animator.animate(70)

中获取每个班级70的动态价值

Jsfiddle完整代码

https://jsfiddle.net/fdharsi/bx9pbLpd/10/

问题已修复现在更新了jsfiddle

https://jsfiddle.net/fdharsi/bx9pbLpd/11/

1 个答案:

答案 0 :(得分:0)

那么你可以简单地将你的<span>元素包装在一个div中,例如:

<div class='percents'>
    <span class="countPercentage" data-value=98">98%</span>
    <span class="countPercentage" data-value=92">92%</span>
    <span class="countPercentage" data-value=12">12%</span>
    <span class="countPercentage" data-value=67">67%</span>
</div>

然后你可以用JQuery循环遍历那个div的子代:

$('.percents').children().each(function() {
    animator.animate($(this).data('value'));
});

您甚至可以简单地做$('.countPercentage').each(),但我还没有检查过......

然而,这可能不是你应该怎么做的......你想要做的是什么?