2014-02-19 37 views
0

我的標題可能有點混亂,但我想要做的是使用滾動函數來確定元素何時進入視口並且每次指定的元素進入時運行每個函數。但我只想讓該功能運行一次。使用.on('scroll')和.each()函數每個運行一次

$(window).on('scroll', function() { 
     $('.counter').each(function(index, value) { 
      triggerpoint = $(window).height() * .8 + $(window).scrollTop(); 
      counterElement = $(this).offset().top; 
      if(counterElement < triggerpoint) { 
       $(this).countTo(); 
      } 
     }); 
}); 

的問題是,每次我把它的滾動時間一次又一次運行.counter元素的.countTo()功能。 我只希望.countTo()函數爲每個.counter元素運行一次。

任何幫助或想法?

+0

哪裏是countTo功能 –

+0

分享您的HTML代碼,請 –

+0

我覺得你需要calc下triggerpoint出的for循環。但它只是一個瘋狂的猜測你需要提供更多的JS和HTML。 – Neha

回答

2

所以我最終找到了解決這個問題的方法。 一旦函數運行一次,我只是添加了一個「元素可見」類。 然後,我在開頭添加了一個簡單的.hasClass語句,以確定元素是否已經通過該函數運行。

$(window).on('scroll', function() { 
$('.counter').each(function(index, value) { 
if ($(this).hasClass("element-visible")) { 
    // do nothing 
    } 
    else { 
    triggerpoint = $(window).height() * .8 + $(window).scrollTop(); // Call point in Viewport: viewport height * decimal(%) + pixels to top of window 

    counterElement = $(this).offset().top; 
    if (counterElement < triggerpoint) { 
    $(this).addClass("element-visible"); 
    $(this).countTo(); 
    } 
    } 
    }); 
}); 
}); 
相關問題