2013-09-16 54 views
1

我正在玩一個進度環,我似乎無法讓它在計時器上運行。我試圖讓進度環自動傳播,比如說0.5秒,從0%到我設定的任何百分比(本例中爲65%)。如何使用JS將計時器綁定到進度環?

我使用這個進度環作爲基礎:http://llinares.github.io/ring-progress-bar/

這是我的小提琴:http://jsfiddle.net/gTtGW/

我試圖使用定時器功能,但我可能沒有被整合,妥善。在小提琴中,我添加了:

for (var i = 0; i< 65; i++){ 
     range += i; 
     setTimeout(timer,800); 
    } 

但是,這打破了進度環。我認爲任何時候更新範圍(用+ = i),繪圖函數都會被調用。我究竟做錯了什麼?提前謝謝你。

回答

0

如果你不打算使用input[type=range]元素,您可以將代碼改成這樣:

(function (window) { 
'use strict'; 

var document = window.document, 
    ring = document.getElementsByTagName('path')[0], 
    range = 0, 
    text = document.getElementsByTagName('text')[0], 
    Math = window.Math, 
    toRadians = Math.PI/180, 
    r = 100; 

function draw() { 
    // Update the wheel giving to it a value in degrees, getted from the percentage of the input value a.k.a. (value * 360)/100 
    var degrees = range * 3.5999, 
     // Convert the degrees value to radians 
     rad = degrees * toRadians, 
     // Determine X and cut to 2 decimals 
     x = (Math.sin(rad) * r).toFixed(2), 
     // Determine Y and cut to 2 decimals 
     y = -(Math.cos(rad) * r).toFixed(2), 
     // The another half ring. Same as (deg > 180) ? 1 : 0 
     lenghty = window.Number(degrees > 180), 
     // Moveto + Arcto 
     descriptions = ['M', 0, 0, 'v', -r, 'A', r, r, 1, lenghty, 1, x, y, 'z']; 
    // Apply changes to the path 
    ring.setAttribute('d', descriptions.join(' ')); 
    // Update the numeric display 
    text.textContent = range; 
    range++; 
    if(range > 100) { 
     clearInterval(timer); 
    } 
} 

    // Translate the center axis to a half of total size 
    ring.setAttribute('transform', 'translate(' + r + ', ' + r + ')'); 

var timer = setInterval(draw,100); 

}(this)); 

基本上改變range到簡單變量從0開始,並且每次調用draw()時增加其值。創建間隔(命名爲timer),以每0.1秒這種情況下運行(當然它給你),並從draw()在適當的時候清除該區間...

JSFiddle Demo

+0

謝謝!我忘記更新我刪除輸入的小提琴。你知道計時器是否也可以設置在立方貝塞爾上嗎? –

+0

@AtalayaCavallo @AtalayaCavallo歡迎您,不錯,它也應該是可能的,計時器和使圓圈一起工作但不相關的功能,所以你可以創建一個不同的圖形/曲線/任何東西,只要你使用正確的數學代碼... – DarkAjax

0

我想你想要的東西,如:

function inc() { 
    var val = parseInt(range.value, 10) 
    range.value = val + 1; 
    draw(); // updating the value doesn't cause `onchange`. 
    if (val < 100) { // don't go over 100 
     setTimeout(inc, 100); 
    } 
} 
inc();