How to fix a header on scroll

后端 未结 12 577
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 11:26

I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.

Can I do this using just css and html or do i need jquery too?

12条回答
  •  感动是毒
    2020-11-27 12:11

    You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

    HTML

    CSS

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

    jQuery

    $(window).scroll(function(){
      var sticky = $('.sticky'),
          scroll = $(window).scrollTop();
    
      if (scroll >= 100) sticky.addClass('fixed');
      else sticky.removeClass('fixed');
    });
    

    Example fiddle: http://jsfiddle.net/gxRC9/501/


    EDIT: Extended example

    If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

    var stickyOffset = $('.sticky').offset().top;
    
    $(window).scroll(function(){
      var sticky = $('.sticky'),
          scroll = $(window).scrollTop();
    
      if (scroll >= stickyOffset) sticky.addClass('fixed');
      else sticky.removeClass('fixed');
    });
    

    Extended example fiddle: http://jsfiddle.net/gxRC9/502/

提交回复
热议问题