【问题标题】:How to add a class to a each li whenever you scroll to it with jquery每当您使用 jquery 滚动到每个 li 时,如何向每个 li 添加一个类
【发布时间】:2021-12-29 21:33:48
【问题描述】:

我有一个列表,里面有很多 li 只有当我滚动到特定的 li 时,我才想为每个 li 添加一个类 问题是,一旦我滚动到其中的一个,该类就会添加到每个 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++;
  }});

提前致谢

【问题讨论】:

  • 我修改了您的代码,它似乎可以按我的意愿工作。 jsfiddle.net/7x2qzg40/1 虽然您显然需要以某种方式添加已在屏幕上加载的 li。

标签: javascript jquery class scroll


【解决方案1】:

我找不到您的代码有什么问题,所以我制作了另一个版本的代码。你可以在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
    });

  })

【讨论】:

  • 非常感谢。有用。我很感激。
【解决方案2】:

考虑以下内容。

$(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 是元素本身。

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多