首先,抱歉,因为我知道这个问题有太多问题,但我找不到我需要的答案。 我想创建一个侧边栏,就像 Facebook 的左侧边栏一样,当我滚动时,侧边栏会在显示所有内容时保持不变。 我知道还有一篇关于此的文章(Sticky Sidebar Like Facebook how to add offset?)但它不起作用。 所以我希望在这里找到答案。 (如果有 javascript,而不是 jquery,那就太好了)。 非常感谢,祝你有美好的一天。 Sicky sidebar
最佳答案
正如@Vince 提到的,position: fixed
是要走的路。但是,您需要进行一些计算才能知道何时设置固定位置。你需要:
- 侧边栏的顶部(如果你有标题或其他东西)
- 侧边栏的高度(计算底部的位置)
- 窗口的高度
- 到目前为止您滚动的距离。
这一切对于 jQuery 来说都非常容易,而对于普通的 JavaScript 来说并不难,只是有点冗长。看看这个片段:
// Define Our Sidebar
const sidebar = document.getElementById("sidebar");
// Get Sidebar Parameters
let sidebarTop = sidebar.offsetTop,
sidebarHeight = sidebar.clientHeight,
sidebarBottom = sidebarHeight - sidebarTop;
// Determine Current Scroll Position
window.onscroll = function(){
let distanceScrolled = document.documentElement.scrollTop,
windowHeight = window.innerHeight,
calculation = distanceScrolled + windowHeight;
if( calculation >= sidebarBottom ){
sidebar.classList.add('sticky');
} else {
sidebar.classList.remove('sticky');
}
}
#sidebar.sticky {
position: fixed;
bottom: 0;
right: 0;
}
* { margin: 0; box-sizing: border-box; }
#content { line-height: 40px; background: linear-gradient(to bottom, #eee, #888); width: 66.66%; }
#sidebar { background: linear-gradient(to bottom, #2bf, #06c); color: #fff; width:33.33%; float: right; height: 175vh; position: relative; min-height: 450px; }
.last-item { position: absolute; bottom: 0; }
.second-item { position: absolute; top: 50%; transform: translateY(-50%); }
<aside id="sidebar">
First Item<br />
<span class="second-item">Sidebar</span><br />
<span class="last-item">Last Item</span><br />
</aside>
<main id="content">
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
Content<br><br><br><br><br><br><br>
</main>
关于javascript - 如何像 Facebook 一样使用 javascript 停止滚动侧边栏(粘性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49584042/