2011-11-21 186 views
5

我希望创建一个粘性标题。 。每当用户向下滚动和原始标题消失,那么“粘”头应该踢在粘性标题 - 滚动 - CSS/jQuery

我目前使用的:

$(function(){ 
    // Check the initial Poistion of the Sticky Header 
    var stickyHeaderTop = $('#sticky').offset().top; 
    $(window).scroll(function(){ 
     if($(window).scrollTop() > stickyHeaderTop) { 
      //$('#sticky').css({position: 'fixed', top: '0px', float: 'right'}); 
      $('#sticky').addClass("sticky"); 
     } else { 
      $('#sticky').removeClass("sticky"); 
     } 
    }); 
}); 

虽然,当前的添加类“粘”每当用户进行滚动时,而不是原始标题应该消失时。

问候

+1

这工作得很好:http://jsfiddle.net/purmou/ZQwhL/embedded/result – Purag

+0

但我原来的报头位于在顶部开始。 – oliverbj

+6

如果它位于顶部,那么为什么用户必须滚动才能使其变得粘滞?只需将其设置为'position:fixed;'即可开始:http://jsfiddle.net/purmou/ZQwhL/1/embedded/result,html,css/ – Purag

回答

3

把他裹好了divid="whateveryouwannacallit"

,并设置:

#whateveryouwannacalltit{ 
position:fixed; 
top:0; 
left: 0; 
width:100%; 
} 
1

其实,你不需要包装。下面是代码

$(document).ready(function() { 
    var stuck = $('#header'); 
    var start = $(div).offset().top; 
    $.event.add(window, "scroll", function() { 
    var p = $(window).scrollTop(); 
    $(stuck).css('position',((p)>start) ? 'fixed' : 'static'); 
    $(stuck).css('top',((p)>start) ? '0px' : ''); 
    }); 
}); 

幸得此页:http://viralpatel.net/blogs/scroll-fix-header-jquery-facebook/