2009-10-26 14 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高的值。您必須確保在進行函數調用之前不會發生這種情況。