Javascript 使用.on(';scroll';)和.each()函数,每个函数每次运行一次
我的标题可能有点混乱,但我尝试使用一个滚动函数来确定元素何时进入视口,并在指定元素每次进入时运行each函数。但我只希望函数运行一次Javascript 使用.on(';scroll';)和.each()函数,每个函数每次运行一次,javascript,jquery,scroll,each,Javascript,Jquery,Scroll,Each,我的标题可能有点混乱,但我尝试使用一个滚动函数来确定元素何时进入视口,并在指定元素每次进入时运行each函数。但我只希望函数运行一次 $(window).on('scroll', function() { $('.counter').each(function(index, value) { triggerpoint = $(window).height() * .8 + $(window).scrollTop(); counterElem
$(window).on('scroll', function() {
$('.counter').each(function(index, value) {
triggerpoint = $(window).height() * .8 + $(window).scrollTop();
counterElement = $(this).offset().top;
if(counterElement < triggerpoint) {
$(this).countTo();
}
});
});
$(窗口).on('scroll',function(){
$('.counter')。每个(函数(索引、值){
triggerpoint=$(窗口).height()*.8+$(窗口).scrollTop();
计数器元素=$(this).offset().top;
if(计数器元素<触发点){
$(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();
}
}
});
});
});
$(窗口).on('scroll',function(){
$('.counter')。每个(函数(索引、值){
if($(this).hasClass(“元素可见”)){
//无所事事
}
否则{
triggerpoint=$(窗口).height()*.8+$(窗口).scrollTop();//视口中的调用点:视口高度*小数点(%)+到窗口顶部的像素
计数器元素=$(this).offset().top;
if(计数器元素<触发点){
$(this.addClass(“元素可见”);
$(this.countTo();
}
}
});
});
});
count函数在哪里共享您的html代码请我认为您需要计算触发器指向for循环外。但这只是一个猜测,你需要提供更多的js和html。