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



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

提前感谢

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

考虑以下内容。

$(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");
}
});
});

这是未经测试的,因为你没有提供一个最小的,可复制的例子。

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

最新更新