我有一個包含許多 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 ;
}});
提前致謝
uj5u.com熱心網友回復:
我找不到你的代碼有什么問題,所以我制作了你的代碼的另一個版本。您可以在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
});
})
uj5u.com熱心網友回復:
考慮以下。
$(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是元素本身。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398275.html
標籤:javascript 查询 班级 滚动
