2015-07-18 114 views
0

我有一段代碼依賴於滾動位置,運行。問題在於它每次用戶滾動時都會運行,這很煩人,所以我希望只能運行一次功能,如果if語句(我在例子中做的那個)是真的。我的代碼jquery每次只運行一次

例子:

window.addEventListener("scroll", function() { 
      var  top  = this.scrollY, 
        posWeb = $('section#web').position().top; 

      if(top > posWeb){ 
       $('div.test').each(function(){ 
        $(this).animate({ 
         width:'100%' 
        }, 1000); 
       }); 
      } 
     }, false); 

我曾經試過一次()的每個函數之前推杆,但不幸的是不起作用。建議? :)

回答

1

一個簡單的標誌變量會照顧它。

var animated=false; 

window.addEventListener("scroll", function() { 
    var top = this.scrollY, 
     posWeb = $('section#web').position().top; 
    // new condition added 
    if (top > posWeb && !animated) { 
     animated = true; // set true now so animations don't get attempted again 
     $('div.test').each(function() { 
      $(this).animate({ 
       width: '100%' 
      }, 1000); 
     }); 
    } 
}, false); 

one()僅用於事件,而不是動畫

+0

哦偏離航向。我怎麼沒有想到這個?非常感謝 :-) – simon