2015-12-13 48 views
1

我正在製作一個計數器,以便當頁面滾動到某個位置時,計數器開始並且動畫到已經在HTML中設置的數字。如何在頁面到達某個位置時啓動計數器?

我在編程一個完整的新手,並想知道我怎麼動畫櫃檯。另外,我如何獲得頁面滾動的位置。 同樣在我的代碼中,我不知道我的邏輯是否正確,但我的setInterval根本不工作。我如何繼續?

http://jsfiddle.net/a1t5m48f/2/

function Counter() { 
    this.element = document.getElementsByClassName('counter-number'); 

    var intervalId; 

    var that = this; 

    this.init = function() { 
    for (var i = 0; i < that.element.length; i++) { 
     intervalId = setInterval(that.animate(i), 1000); 
    } 

    } 

    this.animate = function(i) { 
    var j = 0; 
    that.element[i].innerHTML = j; 
    j++; 
    if (j == parseInt(that.element[i].innerHTML)) { 
     clearInterval(intervalID); 
    } 
    console.log('hello'); 
    } 

} 

var counter = new Counter(); 
counter.init(); 

回答

1

使用一種setTimeout()定時器更優選爲大於數setInterval()定時器。在存儲在內部屬性中的.init()方法計數器目標值中,當前值設置爲零。存儲在.indices陣列中的活動計數器索引。當在.animate()中達到目標值時,計數器元素索引將從該數組中移除。如果數組中有一些活動計數器,我們設置一個新的計時器以在延遲之後調用下一次迭代。動畫停止在空.indices陣列上。

var counter; 
var pos = 200; 

function Counter() { 
    this.element = document.getElementsByClassName('counter-number'); 
    this.currentValues = []; 
    this.targetValues = []; 
    this.indices = []; 
    var that = this; 

    this.init = function() { 
    var value; 
    for (var i = 0; i < that.element.length; i++) { 
     that.indices.push(i); 
     that.targetValues.push(parseInt(that.element[i].innerHTML)); 
     that.currentValues.push(0); 
     that.element[i].innerHTML = '0'; 
    } 
    setTimeout(that.animate, 1000); 
    } 

    this.animate = function() { 
    var value; 
    var index; 
    var indicesToRemove = []; 
    for (var i = 0; i < that.indices.length; i++) { 
     index = that.indices[i]; 
     if (that.currentValues[index] < that.targetValues[index]) { 
     that.currentValues[index]++ 
     that.element[index].innerHTML = that.currentValues[index].toString(); 
     } else { 
     indicesToRemove.push(i); 
     } 
    } 

    while (indicesToRemove.length > 0) { 
     i = indicesToRemove.pop(); 
     that.indices.splice(i, 1); 
    } 

    if (that.indices.length > 0) { 
     setTimeout(that.animate, 1000); 
    } 
    } 
} 

window.onscroll = function() { 
    if ('undefined' === typeof counter 
    && (document.body.scrollTop > pos || document.documentElement.scrollTop > pos) 
) { 
    counter = new Counter(); 
    counter.init(); 
    } 
} 
0
function whatsMyPosition(){ 
    scrollPosition = { 
     y: window.pageYOffset 
    } 
    scrollPosition.y === something ? do Something; 
} 
+0

沒了,只允許使用普通的JavaScript。 –

+0

window.scrollTo(); – KornholioBeavis

相關問題