如何在使用 jquery 滚动到每个 li 时向其添加 class

How to add a class to a each li whenever you scroll to it with jquery

我有一个包含很多行的列表 我只想在滚动到特定 li 时向每个 li 添加 class 问题是 class 被添加到每个 li 一旦我滚动到其中的一个

  $(window).scroll(function(e) {
  var y = $(document).scrollTop();
  var h = $(window).height();
  var t = $('li.product');
  var length = t.length;
  for(var i=1;i <= length;){
    var number = 'li.product:nth-child('+i+')';
      if(y + h > $(number).position().top){
        $(number).addClass("animate__animated animate__fadeInDown");
      }
      i++;
  }});

提前致谢

考虑以下因素。

$(window).scroll(function(e) {
  var y = $(document).scrollTop();
  var h = $(window).height();
  var t = $('li.product');
  t.each(function(i, el) {
    if ((y + h) > $(el).position().top) {
      $(el).addClass("animate__animated animate__fadeInDown");
    }
  });
});

这是未经测试的,因为您没有提供 Minimal, Reproducible Example

使用.each()我们可以迭代每个元素。 i 是索引,el 是元素本身。

我找不到你的代码有什么问题,所以我制作了你的代码的另一个版本。您可以在 https://codepen.io/beneji/pen/RwLQLVV.

找到它

该代码使用 .each 而不是更适合这种情况的 for 循环。

您可以根据您的具体情况调整此代码。

$(window).scroll(function(){ 
    
    const scrolling_position = $(window).scrollTop()
    const window_height = $(window).height()
    
    $("li.product").each(function(){
      const product_position = $(this).position().top
      if(product_position <= scrolling_position + window_height)
        $(this).addClass("animate__animated animate__fadeInDown") // replace this by whatever class you want
    });

  })