Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用.on(';scroll';)和.each()函数,每个函数每次运行一次_Javascript_Jquery_Scroll_Each - Fatal编程技术网

Javascript 使用.on(';scroll';)和.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

我的标题可能有点混乱,但我尝试使用一个滚动函数来确定元素何时进入视口,并在指定元素每次进入时运行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();
           }
      });
});
$(窗口).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。