2013-05-05 55 views
0

啓停JavaScript函數我有我的網站下面的代碼....由定時器

首先,我將如何開始通過單擊鏈接而動畫/功能?

然後,我將如何「凍結」動畫中的最後一幀? (可能由定時器?)

謝謝。

HTML標記:

<div id="anim"></div> 

CSS:

#anim { 
width: 14px; height: 14px; 
background-image: url(http://mail.google.com/mail/im/emotisprites/wink2.png); 
background-repeat: no-repeat; 
} 

的Javascript:

var scrollUp = (function() { 
    var timerId; // stored timer in case you want to use clearInterval later 

    return function (height, times, element) { 
    var i = 0; // a simple counter 
    timerId = setInterval(function() { 
     if (i > times) // if the last frame is reached, set counter to zero 
     i = 0; 
     element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up 
     i++; 
    }, 100); // every 100 milliseconds 
    }; 
})(); 

// start animation: 
scrollUp(14, 42, document.getElementById('anim')) 

這裏有一個小提琴:http://jsfiddle.net/ctF4t/

回答

1

您的代碼已經爲所製備,讀取的第二行:

var timerId; // stored timer in case you want to use clearInterval later 

的setInterval被用來定義在 一定的時間間隔再次並再次運行的功能。 clearInterval用於阻止這一點。在 動畫的結束,而不是重置幀計數器i爲0,我們可以使用clearInterval 停止動畫一起:

 if (i > times) { 
      clearInterval(timerId); 
     } 

這裏有一些額外的輸出用於調試的小提琴:http://jsfiddle.net/bjelline/zcwYT/

0

喜你可以返回js對象句柄開始和結束..因爲timerId充當私人我們不能從外部訪問函數。

var scrollUp = (function() { 
    var timerId, height, times ,i = 0 , element; 

    return { 
     stop : function(){ 
      clearInterval(timerId); 
     }, 
     init :function(h, t, el){ 
      height = h; 
      times = t; 
      element =el ; 
     }, 
     start : function () { 
      timerId = setInterval(function() { 
       // if the last frame is reached, set counter to zero 
       if (i > times) { 
       i = 0; 
       } 
       //scroll up   
       element.style.backgroundPosition = "0px -" + i * height + 'px'; 
       i++; 
      }, 100); // every 100 milliseconds 
      } 
    }; 
})(); 

請參閱完整操作http://jsfiddle.net/ctF4t/1/。希望這會幫助你