0

在我的投票系统中,我想显示投票百分比。这个百分比在 ajax 请求(成功响应)中给出并计算。我想创建一个像向上和向后的实时计数器(如果投票百分比或多或少)。

比方说,投票现在是 40,成功响应返回 50,我想显示计数器从 40 计数到 50(动画)。

我试过这个:

<b class="countPercentage">40%</b>

$('.countPercentage').animated().text(data.percentage);

但没有成功,它只是将值从 40 更改为 50。

提前致谢!缺口

4

3 回答 3

2

您需要自己创建计数器。当然时间是可以调整的,可能根据数量来调整diff

JavaScript

var display = $('.countPercentage > span');

var currentValue = parseInt(display.text());
var nextValue    = data.percentage;

var diff         = nextValue - currentValue;
var step         = ( 0 < diff ? 1 : -1 ); 

for (var i = 0; i < Math.abs(diff); ++i) {
    setTimeout(function() {
        currentValue += step
        display.text(currentValue);
    }, 100 * i)   
}

演示

先试后买

于 2013-09-27T12:31:29.290 回答
0

另一种创建您自己的百分比计数器的方法(您可以在http://jsfiddle.net/CEbGA/上看到它的实际效果):

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);
于 2013-09-27T12:59:15.303 回答
0

超级晚了,但是,我在我的方形空间中使用了一个类似的。只是不是百分比。我对编码知之甚少,无法知道差异,但嘿,这是 HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
var a = 0;
$(window).scroll(function() {

var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');
  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },
    {
      duration: 2000,
      easing: 'swing',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
      }
      });
 });
 a = 1;
 }
 });
 </script>
<div id="counter">
 <div class="sqs-col sqs-col-4 counter-value" data-count="58" data-
 desc=>0</div>  
<div class="sqs-col sqs-col-4 counter-value" data-count="42" data-
 desc=>0</div>
<div class="sqs-col sqs-col-4 counter-value" data-count="88" data-
desc=>0</div>
</div>


<style>
  .counter-value { 
font-size: 60px;
line-height:2em;
text-align:center;
padding:17px 0;
 }
.counter-value:after {
content: attr(data-desc);
display:block;
text-transform:uppercase;
font-size: 14px;
line-height:1.2em;
于 2017-10-22T04:50:22.290 回答