【问题标题】:Compare variable (scroll position) to individual numbers in array jQuery将变量(滚动位置)与数组 jQuery 中的单个数字进行比较
【发布时间】:2020-01-15 03:59:47
【问题描述】:

我有一个数组(它是页面上未知数量元素的偏移位置)。我希望能够在用户向下滚动页面上的这个像素数时添加/删除类。

var offsetPositions = [200,500,700,1000,1100,1500];

$(window).scroll(function(){
  var scrolled  = $(window).scrollTop();
});

问题是数组中的偏移位置是顶部和底部偏移位置。所以使用上面的例子,第一个元素的顶部是 200 像素,底部是 500 像素。下一个顶部为 700 像素,底部为 1000 像素。所以它们是成对的,而且总是有偶数个。

我需要滚动位置到达数组中的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
}

类的最终结果仅在项目被滚动传递时才存在,而不是介于两者之间。

我不知道如何在滚动函数中为数组添加一个 for 循环来满足我的需要。我还考虑将数组拆分为奇数和偶数,但是尝试以我想要的方式比较两个数组更加复杂。我只是在寻找有关如何使用它的建议,或者我是否忽略了一些明显的东西。

【问题讨论】:

  • 你为什么不用var offsetPositions = [[200,500],[700,1000],[1100,1500]];

标签: jquery for-loop scrolltop


【解决方案1】:

根据数组的索引确定添加或删除类

当索引为偶数时添加类

当索引为奇数时删除类

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
    }

  });
});

【讨论】:

    【解决方案2】:

    您可以尝试这种方式来实现它(通过使用two dimensional array in JavaScript

    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();
      var index = 0;
      offsetPositions.forEach(pairs => {
        if(scrolled > pairs[0]) console.log("Add class" + index);
        if(scrolled > pairs[1]) console.log("Remove class" + index);
        index += 1;
      }); 
      
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div style="height: 2000px; overflow-y:scroll;" id="demo">
    
    <div style="height: 200px; background-color:red">height 200</div>
    
    <div style="height: 300px; background-color:green">height 300</div>
    
    
    <div style="height: 200px; background-color:blue">height 200</div>
    
    
    <div style="height: 300px; background-color:orange">height 300</div>
    
    </div>

    【讨论】:

    • 这能回答你的问题吗?如果您需要任何帮助,请告诉我@david browne
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2012-08-08
    相关资源
    最近更新 更多