滚动固定侧边栏,然后在滚动后取消修复

时间:2021-04-27 03:52:06

标签: javascript html jquery user-interface

我正在尝试模仿本网站的一个功能: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
        }
    });

1 个答案:

答案 0 :(得分:2)

您可以结合使用 sticky 和 ​​IntersectionObserver 来实现这一点,这样就不必不断寻找用户是否正在滚动和进行调整。

固定/浮动框最初设置为粘性,这意味着当您向下滚动时,它会粘在视口的顶部。然后,页脚上的交叉点观察者将框设置为相对(“解除它”),因此随着页脚被更充分地显示,它会向上移动。当页脚滚动到视线之外时,该框会恢复为粘性状态。

这是一个简单的设置来演示:

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>

相关问题