使用 JQuery 制作动画数字(半倒计时)?
-
06-07-2019 - |
题
我正在尝试使用 JQuery 将一个数值(例如 5000)快速更改为另一个值(例如 4000)。现在我用以下方法做得很好:
mod(".class",4000,"add");
function mod(id,value,type){
var numb = $(id).html();
var current_value = parseInt(numb);
do {
if(type == "add")
increment(id);
else
decrement(id);
current_value = parseInt(numb);
}while(current_value != value);
function decrement(id){
$(id).html(current_value-1);
}
function increment(id){
$(id).html(current_value+1);
}
}
我知道这可能不是最好的方法,但我需要它做的是从当前值到设定值非常快速地倒计时(或向上)数字。我使用此方法的目的是使用 setInterval 或 setTimeout 进行延迟,但这会使整个脚本严重失败。
任何建议都是值得赞赏的,但是我不希望使用大型插件来完成这个看似简单的任务。
解决方案
当我运行你提供的代码时,我陷入了无限循环。在do循环结束时,你有
current_value = parseInt(numb);
但是numb的值只在函数的开头设置,所以它会永远持续下去。如果您将其更改为
current_value = parseInt($(id).html());
然后它工作正常。除了它似乎立即发生。
我修改了一个方法,使用似乎运行得相当好的超时来实现动画,但是因为我仍然是javascript的新手,我不知道是否有更高效的方法。只需调整传递给setTimeout的第二个参数即可获得所需的速度。如果你想改变增量/减量值,只需改变 dir
的减速度。
function mod2(id, value) {
var numb = $(id).html();
var current_value = parseInt(numb);
// determine direction to go
var dir = 1;
if (current_value - value > 0) {
dir *= -1;
}
getThere(id, current_value, value, dir);
}
function getThere(id, current_value, target_value, dir) {
current_value += dir;
$(id).html(current_value);
if (current_value != target_value) {
setTimeout("getThere('"+id+"',"+current_value+","+target_value+","+dir+")", 10);
}
}
其他提示
您在这里做的是快速连续多次更新DOM。因此,浏览器将等待您完成所有更改,然后才会重新绘制页面。因此,在数字一直下降到4000之前,您不会看到任何视觉变化。
是的,您需要使用 setTimeout
或 setInterval
/ clearInterval
。或者,为了清晰的代码,您可以使用 jQuery“wait”等。插件:
// (code to get new value goes here)
$('.class').wait(100, function(){
$(this).text(newValue);
});
我使用 text()
代替 html()
,因为看起来你不需要改变任何HTML结构。
我喜欢 thorn 的 setTimeout 方法,但我会将其压缩为 2 个函数,并在窗口加载后启动它,以确保页面在更新计数器之前已加载:
var counterTimeout = 10; // time between increments in ms
$(window).load(function() {
mod('class', 'add', 4000);
});
function mod(class, type, targetVal) {
var $class = $(class);
var numb = parseInt($class.html());
numb = (type == 'add') ? numb + 1 : numb - 1;
$class.html(numb);
if (numb != targetVal) {
setTimeout('mod("' + class + '","' + type + '",' + targetVal)', counterTimeout);
}
}
如果 $class.html() 在“add”的情况下以高于 targetVal 的值开始,或者在其他情况下以低于 targetVal 的值开始,则不满足基本情况。您必须确保在调用函数之前不会发生这种情况。