How does the js scroll bar judge in an array?

in order to make a scrolling page, it is similar to the lazy loading effect.

The

page has many P tags, gets the offsetTop location values of all P tags, and saves the array

    var items=$("p");
    var arr_h = [];    
    for (var i=0; i<items.length; iPP){
            arr_h.push(items[i].offsetTop);
    }; 

the result is:

console.log(arr_h); [16, 548, 1080, 1612]

then get the scroll bar drop-down position, the question is, how to write judgment?

    $(window).scroll(function(){
        
      var scrollTop = $(document).scrollTop();
      //console.log(scrollTop);  0 1 2 3 .....100....1000
        
     //    
     if(scrollTop == arr_h){
     
        console.log();
     }else{
     
       console.log();
     }

    });
Sep.26,2021

the landlord must want to know where the current scrolling position is located

for example, [16,548,1080,1612] , what do you do when you are at 0such 15 , what do you do when 160548 , and so on

then you can deal with

in this way.
const pos = function(value){
    return value<=16&&'1'||value<=548&&'2'||value<=1080&&'3'||value<=1612&&'4'||'5'
}

pos(17);  //'1'
pos(177);  //'2'

so that you know which interval you are in, and then deal with it separately

the above judgment process can also be looped according to the array. I just wrote a demonstration here


how can an array be equal to a number? you can use the indexOf of the array

var scrollTop = $(document).scrollTop();

if (arr_h.indexOf(scrollTop)>-1){
     
    console.log();
 }else{
 
   console.log();
 }

arr_h is an array that cannot be compared, and should not be used = = use > =


replace what you write wrong so that you can judge, but it is not recommended to use the same way
because the chance that scrollTop happens to be equal to one of the offsetTop of p is very small

var match = arr_h.filter(function(v){return v===scrollTop})
if(match.length === 1) {
  console.log(match[0])
}
Menu