首页 > 解决方案 > 滚动固定侧边栏,然后在滚动后取消固定

问题描述

我试图模仿这个网站的一个功能: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
        }
    });

标签: javascripthtmljqueryuser-interface

解决方案


您可以结合使用 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>


推荐阅读