Sticky NavBar onScroll?

前端 未结 5 900
失恋的感觉
失恋的感觉 2021-01-06 11:06

I\'m currently building a site for myself, and I found this really awesome effect on multiple sites where the navbar is below an image, but when you scroll past it, it stick

5条回答
  •  日久生厌
    2021-01-06 11:47

    Here is a REAL quick example I threw together with jquery and some very simple css.

    JS

    $(window).on('scroll', function(){
        if($(window).scrollTop()>=95 && !$('nav').hasClass('fixed')){
            $('nav').addClass('fixed'); 
        }
        else if($(window).scrollTop()<95 && $('nav').hasClass('fixed')){
           $('nav').removeClass('fixed') 
        }
    });
    

    CSS

    .container {
      height: 1800px;
    }
    
    .header {
      text-align: center;
    }
    
    nav {
      background-color: #efefef;
      border-top: 2px solid #666;
      border-bottom: 2px solid #666;
      padding: 15px;
      width: 100%;
    }
    nav ul {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    nav li {
      display: inline-block;
    }
    
    .fixed {
      position: fixed;
      top: 0;
      left: 0;
    }
    

    HTML

    
    

提交回复
热议问题