开发者

jQuery window scroll and elements in position problem

I'm using the $(window).scroll(function() to set classes on the navigation of a site. When a section rolls into view the navigation class changes to 'current'.

$(window).scroll(function() {

                var top = 0;
                t开发者_开发知识库op = $(window).scrollTop();

                if(top < 1000){
                    $("a[href='#uk']").parent().addClass("current");
                    $("a[href='#uk']").parent().siblings().removeClass("current");
                }
                if((top >= 1000) && (top < 2000)){
                    $("a[href='#mcr']").parent().addClass("current");
                    $("a[href='#mcr']").parent().siblings().removeClass("current");
                }    
                if((top >= 2000) && (top < 3000)){      
                    $("a[href='#lpool']").parent().addClass("current");
                    $("a[href='#lpool']").parent().siblings().removeClass("current");
                }
                if((top >= 3000) && (top < 4000)){      
                    $("a[href='#bham']").parent().addClass("current");
                    $("a[href='#bham']").parent().siblings().removeClass("current");
                }
            });  

This works great, however it works when the window is "scrolled" into place (obviously). If the page is refreshed then the class is removed even though the page remains at a certain section.

How would I get this code to check where it is on page load and apply the class immediately?


   //call it every load.. to fix your problem...
    fix();

    $(window).scroll(fix); //then bind it on window scroll..

 

function fix(){
     var top = 0;
     top = $(window).scrollTop();

     if(top < 1000){
          $("a[href='#uk']").parent().addClass("current");
          $("a[href='#uk']").parent().siblings().removeClass("current");
     }
     if((top >= 1000) && (top < 2000)){
          $("a[href='#mcr']").parent().addClass("current");
          $("a[href='#mcr']").parent().siblings().removeClass("current");
      }    
      if((top >= 2000) && (top < 3000)){      
          $("a[href='#lpool']").parent().addClass("current");
          $("a[href='#lpool']").parent().siblings().removeClass("current");
      }
      if((top >= 3000) && (top < 4000)){      
          $("a[href='#bham']").parent().addClass("current");
          $("a[href='#bham']").parent().siblings().removeClass("current");
      }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜