2014-02-19 35 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(); 
    } 
    } 
    }); 
}); 
}); 
相关问题