首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从零到百分比的jQuery动画数字计数器

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

Stack Overflow用户
提问于 2018-03-16 08:55:08
回答 1查看 2.3K关注 0票数 1

我工作的项目,我想把jQuery动画计数器从零到百分比值- Javascript动画在结果页,值是动态的从数据库?

代码语言: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);
代码语言:javascript
复制
<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中获得每个类70的动态值?

Jsfiddle完整代码

代码语言:javascript
复制
https://jsfiddle.net/fdharsi/bx9pbLpd/10/

问题现在已经得到修正,这里更新了jsfiddle

代码语言:javascript
复制
https://jsfiddle.net/fdharsi/bx9pbLpd/11/
EN

回答 1

Stack Overflow用户

发布于 2018-03-16 09:07:31

您可以简单地将您的<span>元素封装在一个div中,例如:

代码语言:javascript
复制
<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的子程序,如下所示:

代码语言:javascript
复制
$('.percents').children().each(function() {
    animator.animate($(this).data('value'));
});

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49316559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档