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

后端 未结 21 1487
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:48

    You could use simply css, positioning your element as fixed:

    .fixedElement {
        background-color: #c0c0c0;
        position:fixed;
        top:0;
        width:100%;
        z-index:100;
    }
    

    Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero.

    You can detect the top scroll offset of the document with the scrollTop function:

    $(window).scroll(function(e){ 
      var $el = $('.fixedElement'); 
      var isPositionFixed = ($el.css('position') == 'fixed');
      if ($(this).scrollTop() > 200 && !isPositionFixed){ 
        $el.css({'position': 'fixed', 'top': '0px'}); 
      }
      if ($(this).scrollTop() < 200 && isPositionFixed){
        $el.css({'position': 'static', 'top': '0px'}); 
      } 
    });
    

    When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed.

提交回复
热议问题