javascript - 滚动固定侧边栏,然后在滚动后取消固定
问题描述
我试图模仿这个网站的一个功能:https ://johnkingforgovernor.com/home.html
如果向下滚动,右侧会出现一个框,沿着页面向下移动,直到到达页脚。因此,它就像某种逻辑设置了一个固定侧栏的窗口。这是我的代码。
var windowHeight = jQuery(window).height();
var distanceFromTop = jQuery(window).scrollTop();
jQuery(window).on("scroll", function(event){
windowHeight = jQuery(window).height();
distanceFromTop = jQuery(window).scrollTop();
if (distanceFromTop > jQuery("#firstdiv").height() && distanceFromTop < jQuery("#seconddiv").height()) {
// Lock
} else {
// Unlock
}
});
解决方案
您可以结合使用 Sticky 和 IntersectionObserver 来实现这一点,这样就不必不断地寻找用户是否在滚动和进行调整。
固定/浮动框最初设置为粘性,这意味着当您向下滚动时,它会粘在视口的顶部。然后页脚上的交叉点观察者将框设置为相对('unsticks'),因此当页脚更充分地显示时它会向上移动。当页脚滚动到视线之外时,该框恢复为粘性。
这是一个简单的设置来演示:
function observed(entries) {
if (entries[0].isIntersecting) {
box.style.position = 'relative';
box.style.top = 'calc(' + footer.offsetTop + 'px - 100vh - ' + box.parentElement.offsetTop + 'px)';
}
else {
box.style.position = 'sticky';
box.style.top = '0px';
}
}
const box=document.querySelector('#box');
const footer = document.querySelector('footer');
const observer = new IntersectionObserver(observed);
observer.observe(footer);
header {
width: 100vw;
height: 30vh;
background: cyan;
}
.content {
width: 100%;
height: 200vh;
position: relative;
}
#box {
position: sticky;
top: 0;
background: pink;
width: 20vw;
height:10vw;
}
footer {
height: 50vh;
background: lime;
}
<header>HEADER</header>
<div class="content">
<div id="box">FLOATING/FIXED BOX</div>
</div>
<footer>FOOTER</footer>
推荐阅读
- javascript - Shaka Player:忽略空的 AdaptationSet
- wpf - 有没有办法将日期选择器文本框绑定到 resx 文件和密钥,并且仍然保持作为日期选择器的功能?
- apache - Apache 上的“状态”参数是什么?
- javascript - 将内容下移到固定位置标题后面
- php - 如何过滤数组php
- javascript - 为什么我在网站上上传时我的 jQuery 不起作用
- javascript - 在 pentaho 或 Javascript 中每行添加 2 分钟
- sql - 如何创建具有对象类型的表?
- web-scraping - 如何阻止爬虫
- dns - 如何在浏览器中不显示目标 URL 的情况下将域转发到 Cloudfront URL?