Sticky Header - Scroll - CSS / jQuery

人盡茶涼 提交于 2019-12-04 13:51:46

问题


I wish to create a sticky header. Everytime that the user scrolls down AND the original header goes away, then the "sticky" header should kick in.

I currently use this:

$(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");
        }
    });
});

Although, the current one add the class "sticky" whenever a user just does a scroll, and not when the original header should be gone.

Regards


回答1:


Wrap him with a div with id="whateveryouwannacallit"

and set:

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



回答2:


Actually, you won't need wrapping. Here is the code

$(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' : '');
  });
});

Credit goes to this page: http://viralpatel.net/blogs/scroll-fix-header-jquery-facebook/



来源:https://stackoverflow.com/questions/8214380/sticky-header-scroll-css-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!