如何使一节固定在滚动和向上滚动页脚



我为几个项目获取了这个问题。我试图在StackOverflow上找到解决方案,但有两个部分

  1. 在卷轴上固定
  2. 使用页脚向上滚动
  3. 最后,找出并尝试分享

希望它能帮助其他人。

<div class="col-md-5 offset-md-1">
<div id="listing_preview">
...
</div>
</div>

页脚

<footer class="p-5 footer">
....
</footer>

我研究了这个问题并找到了这个解决方案。CSS

<style>
div.sticky {
position: fixed;
top: 50px;
}
</style>
<script>
window.onscroll = function() {myFunction()};

var product_preview = document.getElementById("listing_preview");
var sticky = product_preview.offsetTop;

function myFunction() {
if (window.pageYOffset > sticky +100) {
product_preview.classList.add("sticky");
} else {
product_preview.classList.remove("sticky");
}
}

var originalBottom = 30; // get this depending on your circumstances
var footerHeight = $('.footer').height() // get this depending on your circumstances
$(window).scroll(function () { // start to scroll
// calculating the distance from bottom
var distanceToBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if (distanceToBottom <= footerHeight) // when reaching the footer
$("#listing_preview").css('top', '-'+ (footerHeight - distanceToBottom) + 'px');
else // when distancing from the footer
$("#listing_preview").css('top',  originalBottom + 'px'); 
// only need to specify 'px' (or other unit) if the number is not 0
});
</script>

最新更新