2013-05-13 116 views
0

当导航位置和滚动位置相等时,我想修正导航位置。滚动时修复导航位置

请让我知道如何获得导航和页面滚动位置的位置?我想是这样的:http://new.livestream.com/live-video-tools

我已经试过:

$(function() { 

    // grab the initial top offset of the navigation 
    var sticky_navigation_offset_top = $('#main-heading').offset().top; 

    // our function that decides weather the navigation bar should have "fixed" cs s position or not. 
    var sticky_navigation = function(){ 
     var scroll_top = $(window).scrollTop(); // our current vertical position from the top 

     // if we've scrolled more than the navigation, change its position to fixed to stick to top, 
     // otherwise change it back to relative 
     if(scroll_top > sticky_navigation_offset_top) { 
      $('#fixed_nav').css({ 'position': 'fixed', 'top':6, 'left':0, 'width':'100%', 'z-index':999, 'height':80, 'background':'#fff' }); 
     } else { 
      $('#fixed_nav').css({ 'position': '','overflow': 'visible', 'display':'block','height':80}); 
     }   
    }; 

    // run our function on load 
    sticky_navigation(); 

    // and run it again every time you scroll 
    $(window).scroll(function() { 
     sticky_navigation(); 
    }); 
}); 

回答

0

这是旧的,但值得为Google员工的利益答案。

See Fiddle here.

$(function() { 
    var offset = $('#nav').offset().top; 
    var nav = function() { 
     var scroll = $(window).scrollTop(); 
     if (scroll < offset) { 
      $('#nav').css({ 'position': 'relative' }); 
     } 
     else { 
      $('#nav').css({ 'position': 'fixed', 'top': 0 }); 
     } 
    }; 
    nav(); 
    $(window).scroll(function() { 
     nav(); //this ensures we check again every time the user scrolls 
    }); 

}); 

OP - 你可能想通了现在,但我不知道你为什么被检查的#main-heading偏移,然后设置的不同#fixed-nav的位置,这可能是在那里你'问题是。