2014-02-26 48 views
2

我正在開發一個僞隨時間線的工具提示,跟隨時間線到一個新的標記位置。setInterval計數器與jQuery動畫

|--------- 800px ------|------------------- 1200px ----------- | 
A (5000km)    B (20000km)        C (30000km) 

標記A(5000公里)和標記B之間的15000公里一個虛假的差異,但在時間軸上的元件之間的實際距離是800像素。我用一個在12秒內沿這兩點移動的計數器爲指標設置動畫。動畫很簡單,但是我無法弄清楚計數器的間隔,所以它在5000秒開始,在12秒的時間內以20000結束。

這是我的,但計數器完成動畫背後的方式,因爲我無法解決的增量值。

var ttl = 12*1000, 
    startKM = 5000, 
    endKM = 15000, 
    diffDist = endKM-startKM, 
    distanceLoop, 
    txt = $('.counter').text(); 
    increment = diffDist/ttl; 

$('.counter').text(startKM); 

$('.indicator').animate({ left: $('.markB').offset().left }, ttl, 'linear', function() { 
    clearInterval(distanceLoop); 
}); 

function counterLoop() { 

    var num = txt++; 
    // what is the count interval 
    // var num = txt + increment 
    $('.counter').text(num); 
}; 

distanceLoop = setInterval(counterLoop, diffDist/ttl) 

counterLoop(); 

我不知道增量是什麼,所以現在它只是+1櫃檯。這可能是一些基本的東西,我只是沒有看到。

感謝您的幫助!

演示/小提琴:http://jsfiddle.net/7xygy/10/

回答

3

您可以使用.animate()功能的step選項,而不是setInterval

var startKM = 5000, 
    endKM = 15000; 

var startLeft = $('.indicator').offset().left, 
    endLeft = $('.markB').offset().left, 
    ratio = (endKM - startKM)/(endLeft - startLeft); 

$('.counter').text(startKM); 
$('.indicator').animate({ left: endLeft }, { 
    easing: 'linear', 
    duration: 12000, 
    step: function(now) { 
     $('.counter').text(Math.floor(startKM + ((now - startLeft) * ratio))); 
    }, 
    complete: function() { 
     $('.counter').text(endKM); 
    } 
}); 

jsfiddle

+0

開裂當時我的頭這一點。布拉沃:) – deb0rian

+0

做得很好,約翰!我不知道這個步驟回調,並且這個工作更好,因爲我知道setInterval不是100%準確的。在一個版本中我有你的比例,但我應該堅持下去。乾杯! – hybrid9