在我的投票系统中,我想显示一个投票百分比。在ajax请求(成功响应)中给出并计算该百分比。我想创建像现场计数器一样的向上和向后(如果投票百分比或多或少)。
让我们说,投票现在是40,成功回应50回,我想显示反击计数从40到50(动画)。
我试过这个:
<b class="countPercentage">40%</b>
$('.countPercentage').animated().text(data.percentage);
但没有成功,它只将值从40改为50。
提前致谢! 尼克
答案 0 :(得分: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)
}
<强>演示强>
答案 1 :(得分: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);
答案 2 :(得分: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;