我的标题可能有点令人困惑,但我想做的是使用滚动函数来确定元素何时进入视口(viewport),并在每次指定元素进入时运行每个函数。但我只想让该函数运行一次。
$(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
元素运行一次。
有什么帮助或想法吗?
最佳答案
所以我最终找到了解决这个问题的方法。 一旦函数运行一次,我就添加了一个“element-visible”类。 然后我在开头添加了一个简单的 if .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();
}
}
});
});
});
关于javascript - 使用 .on ('scroll' ) 和 .each() 函数每个运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870563/