javascript - 使用 .on ('scroll' ) 和 .each() 函数每个运行一次

标签 javascript jquery scroll each

我的标题可能有点令人困惑,但我想做的是使用滚动函数来确定元素何时进入视口(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/

相关文章:

python - 如何使用 curses 滚动?

Javascript 数组循环创建多个数组而不是 1 个数组

javascript - 无法在 Kendo 窗口上显示加载微调器

jquery - 单击自定义跨度时,复选框值从 0 更改为 1

iphone - 从 UITableview 向上滚动时的操作

java - 在 ListView 中滚动时重复项目

php - 表单已验证但仍在提交但没有值?

javascript - 使用输入按钮创建动态表单

javascript - jquery 下拉列表

jquery - 从外部链接自动打开 Bootstrap Modal