问题
When someone scrolls down our page, at a certain moment a div (with a cta button) comes into view. What i am trying to achieve is that this div, from that moment on, gets 'sticky' and scrolls down with the viewport, at the bottom of the viewport, if the site is beging scrolled down. This div then basically is, but not really, sort of a sticky footer as the rest of the site keeps on scrolling behind it.
Now, i am having no problem in getting the div sticky at the top of the page, but thats not what i am after. It needs to stick at the bottom.
I use bootstrap 3 with affix. I'm almost there, but not quite yet. The following javascript with css almost does the job, but the div, with id cta, jumps down the viewport as soon as the div is visible inside the viewport. From that moment on it scrolls down nicely with the viewport at the bottom, but the jump from top to bottom needs to disappear :)
<div id="affixwrapper">
//stuff thats being wrapped above the div with id cta.
</div>
<div id="cta" data-spy="affix">
<div class="section section-success text-center">
<div class="container">
<div class="row">
<div class="col-md-12">
<a class="btn ban-default">Button text</a>
</div>
</div>
</div>
</div>
</div>
<script>
$('#cta').affix({
offset: {
top: function() { return $('#affixwrapper').height(); }
}
});
</script>
<style>
.affix {
bottom: 0px;
position: fixed;
width: 100%;
background-color: white;
z-index: 777;
}
</style>
回答1:
There is literally a position value called 'sticky' in CSS, no need for jQuery :)
Here's a code snippet (see demo)
<!DOCTYPE html>
<style>
body {
height: 600vh;
margin: 0;
}
#sticky {
position: sticky;
top: 90vh;
left: 0px;
width: 100%;
height: 10vh;
background-color: red;
}
#space {
height: 200vh;
}
#container {
height: 200vh;
}
</style>
<div id="space"></div>
<div id="sticky"></div>
The "sticky" <div>
will be relatively positioned (i.e. positioned as it would be without position: sticky
) right after the "space" <div>
until, as the user scrolls, it reaches the offset specified in top
, that is 90vh
. After that, it'll switch to be position: fixed
at that location.
来源:https://stackoverflow.com/questions/45812361/sticky-div-that-stays-at-bottom-of-the-page-when-page-is-being-scrolled