Make a nav bar stick

前端 未结 11 1351
别跟我提以往
别跟我提以往 2020-11-29 19:44

Make a nav bar stick Make a nav bar stick Make a nav bar stick Make a nav bar stick Make a nav bar stick Make a nav bar stick Make a nav bar stick Make a nav bar stick Make

11条回答
  •  广开言路
    2020-11-29 19:52

    I hope this can help someone. Determine the nav offset through js and then apply sticky position css to nav:

    But first, we will define the styles in the stylesheet, like so.

    .sticky {
        position: fixed;
        width: 100%;
        left: 0;
        top: 0;
        z-index: 100;
        border-top: 0;
    }
    

    Then, we will apply that class to the navigation conditionally with jQuery.

    $(document).ready(function() {
      var stickyNavTop = $('.nav').offset().top;
    
      var stickyNav = function(){
        var scrollTop = $(window).scrollTop();
    
        if (scrollTop > stickyNavTop) { 
          $('.nav').addClass('sticky');
        } else {
          $('.nav').removeClass('sticky'); 
        }
      };
    
      stickyNav();
    
      $(window).scroll(function() {
        stickyNav();
      });
    });
    

提交回复
热议问题