简体   繁体   中英

fixed when scrolling but stop at footer

UPDATE I've been testing a bit with the sticky position but it doesn't work on Safari version 11.1. Safari is the highest browser in analytics. So I guess I'm still looking for a jQuery solution. Although the answer from Michał Sadowski helped allot.


I'm trying to get a fixed element when scrolling but it needs to stop being fixed and start scrolling when it reaches the footer.

I'm using this code: Make scrolling sidebar stop at footer

My CSS, HTML are exactly the same as in this fiddle right now.

But the problem is, my fixed element needs to have an offset of +60 because my header (menu) is 55px in height. I've got the offset to work sort off. Right now, I use the following code.

function sticky_relocate() {
    var window_top = $(window).scrollTop()+60;
    var footer_top = $("#footer").offset().top;
    var div_top = $('#sticky-anchor').offset().top;
    var div_height = $("#sticky").height();

    var padding = 20;  // tweak here or get from margins etc

    if (window_top + div_height > footer_top - padding)
        $('#sticky').css({top: (window_top + div_height - footer_top + padding) * -1})
    else if (window_top > div_top) {
        $('#sticky').addClass('stick');
        $('#sticky').css({top: 60})
    } else {
        $('#sticky').removeClass('stick');
    }
}

$(function () {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This kind of works. But when I reach the #footer the top jumps from 60px to -1.8414 . So the transition isn't seamless. It "jumps" when I reach the footer.

I've tried a whole bunch of things.

  • Like adding 60px to the #sticky div.
  • When It removes the class stick I followed that up with $('#sticky').css({top: 60})

But nothing takes away the "jump" is there anyone who could help me to get this to work or has a similar code snippet?. Thanks in advance!

Okay, it depends a lot on your html structure. But let's say you have it like that:

<div class="container">
  <div class="content">
    <div class="sticky">
    </div>
  </div>
  <div class="footer">
  </div>
</div>

Now, in css:

.content{
  position: relative
}
.sticky{
  position: sticky;
  top: 60px;
}

It should do exactly what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM