我有一个数组(它是页面上未知数量的元素的偏移位置)。当用户在页面上向下滚动此像素数时,我希望能够添加/删除类。
var offsetPositions = [200,500,700,1000,1100,1500];
$(window).scroll(function(){
var scrolled = $(window).scrollTop();
});
东西是数组中的偏移位置是顶部和底部偏移位置。因此,使用上面的示例,第一个元素的顶部为200px,底部为500px。下一个的顶部为700px,底部为1000px。因此它们成对出现,并且永远会有偶数。
我需要在滚动位置到达数组中的1、3、5、7项时效果,而在到达2、4、6、8等位置时不效果。像这样;
if (scrolled > 200) {
// add class
}
if (scrolled > 500) {
// remove class
}
if (scrolled > 700) {
// add class
}
if (scrolled > 1000) {
// remove class
}
作为类的最终结果仅在滚动的项目ar通过时才存在,而在两者之间则没有。
我不知道如何在滚动功能内为数组添加for循环,以提供所需的信息。我也考虑过将数组分成偶数,但尝试以我想要的方式比较两个数组会更加复杂。我只是在寻找有关使用它的建议,或者如果我忽略了明显的内容。
您可以尝试通过这种方式实现
var offsetPositions = [[200,500],[700,1000],[1100,1500]];
offsetPositions.forEach(pairs => {
if(scrolled > pairs[0]) // add class
if(scrolled > pairs[1]) // // remove class
});
确定要通过数组的索引添加或删除类
当索引为偶数时再添加类
如果索引为奇数,则删除类
var offsetPositions = [200,500,700,1000,1100,1500];
$(window).scroll(function(){
var scrolled = $(window).scrollTop();
offsetPositions.forEach((v,i)=>{
if(i%2 == 0 && scrolled > v){
//Add class
}else if(scrolled > v){
//Remove class
}
});
});