如何在jQuery中创建百分比计数器?

时间:2017-06-21 10:08:53

标签: jquery html percentage

我试图创建一个百分比计数器,但它没有做我需要的东西。它只显示100%。但是我需要一步一步显示0到100%!我该怎么改变它?

setInterval(function per(p = 0) {
  for (p = 1; p <= 100; p++) {
    $(".percentage").text(p + "%");
  }
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>

1 个答案:

答案 0 :(得分:11)

问题是因为for循环在几分之一秒内运行,而不管setInterval如何。

要解决此问题,您可以更改逻辑以使用递归,然后将每次迭代延迟1秒,如下所示:

function updatePercentage(p) {
  p = p || 0;
  $(".percentage").text(p + "%");
  if (p < 100) {
    setTimeout(function() {
      updatePercentage(++p);
    }, 1000);
  }
}

updatePercentage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>