Menu ul style change on scroll to div

2019-08-04 13:38发布

问题:

I have a menu with ul's and boxes under it as content, and when I scroll to the first box ul's style change to another style, when I scroll to the second box ul's style change to the same another style and the first ul style return to it's original style and like that. The problem is when I arrive to the end of the page, there's space and there ALL the uls styles should return to it's original style but the problem with the jquery code that the last ul style(for the last box) still as I'm on the last box. As you can see here http://ge.tt/1yoq2sg/v/0?c when I arrive to the end of the page every ul style in the menu should be as the original style but it's not. You can also download the file.

回答1:

I've added an variable endpoint which is set to the offset of the final div plus that divs height, when the page is scrolled beyond this the menutext2 class is removed.

$(function(){

  var offsets = [],
      menuText = $('#menu .menuText'),
      endpoint;

  $("div.contentDiv").each( function(i, div) {
      if(i==$("div.contentDiv").length-1){endpoint=$(div).offset().top+$(div).outerHeight();}
      offsets.push({ id: div.id, offset: $(div).offset().top - 60});
  });

  $(window).scroll(function(e) {
    var start = $(this).scrollTop();
    var end = $(this).scrollTop();
    for ( var div = 0; div < offsets.length; div++ ) {
      if ( start > offsets[div].offset ) { 
        menuText.removeClass('menutext2').addClass('menutext');  

        menuText.filter('[linkId="'+offsets[div].id+'"]').addClass('menutext2').removeClass('menutext');
        }
    }

    if ( start === 0 || $(this).scrollTop()>endpoint) {
    menuText.removeClass('menutext2').addClass('menutext');  
    }


  });
});