![](/img/trans.png)
[英]How to stick the bottom part of a div to top of the screen when scrolling down?
[英]How to make a div stick to top or bottom, depending on how the user is scrolling?
你好。 我知道滾動時將div粘貼到頂部或底部有很多問題,但我的問題更具體。
問題是我希望div保持在頂部或底部,具體取決於用戶滾動的方式。
我制作了這個jsFiddle代碼片段來展示內容的設置方式: https ://jsfiddle.net/DTcHh/6155/。
我想要的結果是:每當用戶滾動時,側面的內容也應該與其他內容同時滾動。 如果側面的內容到達末尾(頂部或底部),那么它應該粘在頂部或底部(取決於內容的末端到達的位置)
例如,在我提供的代碼段中,我希望側面的內容滾動到“固定內容最后”。 可見,然后在用戶向下滾動時粘到底部。 現在,如果用戶向上滾動,我希望旁邊的內容也向上滾動,直到“固定內容優先”。 是可見的,然后堅持到頂部。
側面的Html:
<nav >
<div id="filterAnchor"></div>
<div id="filterScroll" class="fixed_div">
Fixed content First.</br>
Fixed content.</br>
Fixed content.</br>
...
[more "Fixed content."]
...
Fixed content.</br>
Fixed content.</br>
Fixed content Last.</br>
</div>
</nav>
首先,您需要知道滾動方向。 如果我是對的,你想要粘性邊欄滾動內容,但永遠不會看不到。
我編輯了這個小提琴 。
它應該需要一些優化,但我希望你能得到這個想法。 棘手的部分是檢查是否達到了底部,我仍然不確定這是否是正確的方法:
if ($window.height() <= $filterClass.height() + top) {
$filterClass.addClass('stick-bottom');
$filterClass.css('top', '');
}
通過這個更新的小提琴我添加了對不同情況的支持:
1.當副內容長於主要內容時:
默認位置是絕對的。 這不需要javascript才能正常工作。
2.當副面內容長於窗口高度時:
該位置設置為固定。 當向下滾動(內容向上移動)時,邊到達時會粘到底部:
// top means position top of the fixed side
if(top < 0 && fixedHeight + top < windowHeight) {
$filterClass.addClass('stick-bottom');
$filterClass.css('top', '');
} else {
$filterClass.css('top', top+diff);
}
3.當副面內容短於窗口高度時:
該位置設置為固定。 情況如上面的原始答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.