1

我正在从事一个项目,我想在结果页面中添加从零到百分比值的 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);
<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>

问题是 jQuery 函数PercentageAnimator正在工作,但直到 70 才有效?

如何获取每个类countPercentage的动态值animator.animate(70)而不是70

Jsfiddle 完整代码

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

问题已得到修复,这里更新了 jsfiddle

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

1 回答 1

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()但我还没有检查......

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

于 2018-03-16T09:07:31.323 回答