2009-10-26 13 views
0

我试图做一个数值,比如5000,快速切换到另一个价值,说4000,使用JQuery。现在我做使用这个罚款:使用JQuery生成动画数字(半倒数)?

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,但是这会使整个脚本失败。

任何建议表示赞赏,但我宁愿不使用大量插件这个看似简单的任务。

+0

它看起来像你的目标是提供一个可见的倒计时或显示器。抛开代码效率,您提供的代码看起来很实用。你有什么问题? – keithm

+0

恩,应该是“你的” – keithm

回答

2

当我跑到你提供的代码,我陷入了一个无限循环。在做循环结束时,你有

current_value = parseInt(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); 
    } 
} 
3

你在这里做的是多次快速连续更新DOM。因此,浏览器会一直等到您完成所有更改后才重新绘制页面。所以,你将不会看到任何视觉上的变化,直到数去一路下跌到4000

是的,你确实需要使用setTimeoutsetInterval/clearInterval。或者,代码清晰,你可以使用jQuery "wait" plugin

// (code to get new value goes here) 

$('.class').wait(100, function(){ 
    $(this).text(newValue); 
}); 

相反的html(),我用text(),因为它看起来像你不需要更改任何HTML结构。

0

我喜欢刺与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); 
    } 
} 

基本情况ISN”吨满足在事件$ class.html()开始与在另一种情况下的“添加”或低于targetVal的情况下比targetVal高的值。您必须确保在进行函数调用之前不会发生这种情况。