javascript 动画数字递增
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18152719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Animate number incrementing
提问by user2066880
I'm trying to make a simple Javascript animation that increments a number until it reaches the target number. The way I'm doing it right now doesn't work however.
我正在尝试制作一个简单的 Javascript 动画,它会递增一个数字,直到达到目标数字。但是,我现在这样做的方式不起作用。
Here is my code: http://jsfiddle.net/nLMem/4/
这是我的代码:http: //jsfiddle.net/nLMem/4/
HTML
HTML
<div id="number">5</div>
JS
JS
$(document).ready(function() {
var target = 50;
var number = $('#number').text();
while(number <= target) {
setTimeout(function() {
$('#number').text(++number);
}, 30);
}
});
回答by
This is similar to what you want:
这类似于您想要的:
var interval = setInterval(function() {
$('#number').text(number);
if (number >= target) clearInterval(interval);
number++;
}, 30);
Your while loop will cause the script execution to 'freeze' while it does its work. It doesn't poll. The other problem is that you call setTimeout
potentially 50 times. You only need to call setInterval
once, and clear it once you reach your target number.
您的 while 循环将导致脚本执行在其工作时“冻结”。它不投票。另一个问题是您setTimeout
可能会拨打50 次。您只需拨打setInterval
一次,并在达到目标号码后清除。
回答by Meloman
Here is a solution based on user1508519 code with increment / decrement automatically and live updating on my pageafter ajax search/filter :
这是一个基于 user1508519 代码的解决方案,自动递增/递减,并在 ajax 搜索/过滤后在我的页面上实时更新:
function animateResultCount(number, target, elem) {
if(number < target) {
var interval = setInterval(function() {
$(elem).text(number);
if (number >= target) {
clearInterval(interval);
return;
}
number++;
}, 30);
}
if(target < number) {
var interval = setInterval(function() {
$(elem).text(number);
if (target >= number) {
clearInterval(interval);
return;
}
number--;
}, 30);
}
}
calling my function in ajax success :
在 ajax 中调用我的函数成功:
...
success: function(response) {
$('div#results').html(response.html);
animateResultCount($('#rescount').html(),response.newcount,'#rescount');
}
...