How to fix a header on scroll

后端 未结 12 551
佛祖请我去吃肉
佛祖请我去吃肉 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:16

    Just building on Rich's answer, which uses offset.

    I modified this as follows:

    • There was no need for the var $sticky in Rich's example, it wasn't doing anything
    • I've moved the offset check into a separate function, and called it on document ready as well as on scroll so if the page refreshes with the scroll half-way down the page, it resizes straight-away without having to wait for a scroll trigger

      jQuery(document).ready(function($){
          var offset = $( "#header" ).offset();
          checkOffset();
      
          $(window).scroll(function() {
              checkOffset();
          });
      
          function checkOffset() {
              if ( $(document).scrollTop() > offset.top){
                  $('#header').addClass('fixed');
              } else {
                  $('#header').removeClass('fixed');
              } 
          }
      
      });
      

提交回复
热议问题