How can I make a div stick to the top of the screen once it's been scrolled to?

后端 未结 21 1458
Happy的楠姐
Happy的楠姐 2020-11-22 07:12

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place

21条回答
  •  礼貌的吻别
    2020-11-22 07:55

    And here's how without jquery (UPDATE: see other answers where you can now do this with CSS only)

    var startProductBarPos=-1;
    window.onscroll=function(){
      var bar = document.getElementById('nav');
      if(startProductBarPos<0)startProductBarPos=findPosY(bar);
    
      if(pageYOffset>startProductBarPos){
        bar.style.position='fixed';
        bar.style.top=0;
      }else{
        bar.style.position='relative';
      }
    
    };
    
    function findPosY(obj) {
      var curtop = 0;
      if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
          curtop += obj.offsetTop;
          obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
      }
      else if (obj.y)
        curtop += obj.y;
      return curtop;
    }
    * {margin:0;padding:0;}
    .nav {
      border: 1px red dashed;
      background: #00ffff;
      text-align:center;
      padding: 21px 0;
    
      margin: 0 auto;
      z-index:10; 
      width:100%;
      left:0;
      right:0;
    }
    
    .header {
      text-align:center;
      padding: 65px 0;
      border: 1px red dashed;
    }
    
    .content {
      padding: 500px 0;
      text-align:center;
      border: 1px red dashed;
    }
    .footer {
      padding: 100px 0;
      text-align:center;
      background: #777;
      border: 1px red dashed;
    }
    This is a Header
    Hello World!
    This is a Footer

提交回复
热议问题