【问题标题】:jQuery Animated Number Counter From Zero To Percentage ValuejQuery 动画数字计数器从零到百分比值
【发布时间】:2018-03-16 08:55:08
【问题描述】:

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

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

Jsfiddle 完整代码

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

问题已在此处修复,更新 jsfiddle

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

【问题讨论】:

标签: jquery html timer counter animator


【解决方案1】:

你可以简单地将 &lt;span&gt; 元素包装在一个带有类的 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(),但我还没有检查...

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2011-10-16
  • 2012-06-16
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多