【问题标题】:Scrolling fixed sidebar then unfix after scroll滚动固定侧边栏,然后在滚动后取消固定
【发布时间】:2021-07-20 10:10:28
【问题描述】:

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

【问题讨论】:

  • 他们有一个contentright div 容器,根据滚动的位置,他们将fixedfixedBottom 类附加到该容器。他们基本上在 CSS 中的 position: absolute;position: fixed; 之间进行交换。我想这就是您想要在锁定/解锁块中执行的操作。另外,您在这里使用 jquery 的任何特殊原因?只是好奇。
  • @EdgardoRodríguez 我应该改用什么?

标签: javascript html jquery user-interface


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-09-18
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多