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

后端 未结 21 1453
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:51

    I came across this when searching for the same thing. I know it's an old question but I thought I'd offer a more recent answer.

    Scrollorama has a 'pin it' feature which is just what I was looking for.

    http://johnpolacek.github.io/scrollorama/

    0 讨论(0)
  • 2020-11-22 07:52

    sticky till the footer hits the div:

    function stickyCostSummary() {
        var stickySummary = $('.sticky-cost-summary');
        var scrollCostSummaryDivPosition = $(window).scrollTop();
        var footerHeight = $('#footer').height();
        var documentHeight = $(document).height();
        var costSummaryHeight = stickySummary.height();
        var headerHeight = 83;
        var footerMargin = 10;
        var scrollHeight = 252;
        var footerPosition = $('#footer').offset().top;
    
        if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
            stickySummary.removeAttr('style');
            stickySummary.addClass('fixed');
    
        } else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
            stickySummary.removeClass('fixed');
            stickySummary.css({
              "position" : "absolute",
              "top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
          });
        } else {
            stickySummary.removeClass('fixed');
            stickySummary.css({
                "position" : "absolute",
                "top" : "0"
            });
        }
    }
    
    $window.scroll(stickyCostSummary);
    
    0 讨论(0)
  • 2020-11-22 07:53

    You can add 3 extra rows so when the user scroll back to the top, the div will stick on its old place:

    Here is the code:

    if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
        $('.fixedElement').css({'position': 'relative', 'top': '200px'});
    }
    
    0 讨论(0)
  • 2020-11-22 07:54

    I had the same problem as you and ended up making a jQuery plugin to take care of it. It actually solves all the problems people have listed here, plus it adds a couple of optional features too.

    Options

    stickyPanelSettings = {
        // Use this to set the top margin of the detached panel.
        topPadding: 0,
    
        // This class is applied when the panel detaches.
        afterDetachCSSClass: "",
    
        // When set to true the space where the panel was is kept open.
        savePanelSpace: false,
    
        // Event fires when panel is detached
        // function(detachedPanel, panelSpacer){....}
        onDetached: null,
    
        // Event fires when panel is reattached
        // function(detachedPanel){....}
        onReAttached: null,
    
        // Set this using any valid jquery selector to 
        // set the parent of the sticky panel.
        // If set to null then the window object will be used.
        parentSelector: null
    };
    

    https://github.com/donnyv/sticky-panel

    demo: http://htmlpreview.github.io/?https://github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

    0 讨论(0)
  • 2020-11-22 07:54

    Here is another option:

    JAVASCRIPT

    var initTopPosition= $('#myElementToStick').offset().top;   
    $(window).scroll(function(){
        if($(window).scrollTop() > initTopPosition)
            $('#myElementToStick').css({'position':'fixed','top':'0px'});
        else
            $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
    });
    

    Your #myElementToStick should start with position:absolute CSS property.

    0 讨论(0)
  • 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;
    }
    <header class="header">This is a Header</header>
    <div id="nav" class="nav">Main Navigation</div>
    <div class="content">Hello World!</div>
    <footer class="footer">This is a Footer</footer>

    0 讨论(0)
提交回复
热议问题