[英]Sticky sidebar from bottom during scrolling
我打算像側邊欄一樣重新創建 Medium.com。 這就是我現在所擁有的,但還遠未結束。
打開下面的 JSFiddle 更好地理解; 我希望執行以下操作:
position: fixed
,它在不尊重布局的情況下向右側移動。 我該如何解決?position: fixed
。我該如何解決? 我知道有粘性工具包可以完成這項工作,但我不能使用任何插件。
HTML:
<div class="container">
<div class="row">
<div class="col-xs-12">
Header and Menu is placed here.
<hr />
</div>
<div class="col-xs-8">
<p>This is the main body which the user would be scrolling infinitely as more data gets loaded on scroll.</p>
</div>
<div class="col-xs-4">
<div id="sidebar">
<p>
This is the sidebar which I want to stop when it reaches the bottom like the one shown in medium dot com
</p>
</div>
</div>
</div>
</div>
Javascript:
function scrollCheck() {
var $right = $('#sidebar'),
scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
docHeight = $(document).height(),
rightHeight = $right.height(),
distanceToTop = rightHeight - windowHeight,
distanceToBottom = scrollTop + windowHeight - docHeight;
if (scrollTop > distanceToTop) {
$right.css({
'position': 'fixed',
'bottom': (scrollTop + windowHeight > docHeight ? distanceToBottom + 'px' : '0px')
});
}
else {
$right.css({
'position': 'relative',
'bottom': 'auto'
});
}
}
$(window).bind('scroll', scrollCheck);
我會回答你的問題。 首先是編輯過的 Fiddle 。
至於你的問題:
width
和設置position: fixed;
意味着元素寬度不再由父元素設置,而是由視口設置。 因此它會擴展以填充視口中的所有寬度。position: fixed;
在元素原始位置上方滾動時從未被刪除,Js 中更新的 if 語句現在刪除了帶有position: fixed;
的類position: fixed;
在其原始位置上方滾動時。更詳細地了解我所做的更改。
我添加了一個 CSS 類,因此.toggleClass
可用於使函數更.toggleClass
。
.docked-sidebar {
position: fixed;
top: 0;
}
我還更改了 if 語句的條件,以便它們起作用。 使用.offset().top;
獲取側邊欄和頁面頂部之間的距離,同時刪除大多數不需要的其他變量。 最后,我創建了 bool 變量( isDocked
),以便不會多次觸發相同的條件。
var $right = $('#sidebar'),
isDocked = false,
initOffsetTop = $right.offset().top;
function scrollCheck() {
var scrollTop = $(window).scrollTop(),
offsetTop = $right.offset().top;
if (!isDocked && ((offsetTop - scrollTop) < 0)) {
$right.toggleClass("docked-sidebar");
isDocked = true;
} else if (isDocked && scrollTop <= initOffsetTop) {
$right.toggleClass("docked-sidebar");
isDocked = false;
}
}
為了像示例網站一樣堅持底部然后頂部,我建議檢查這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.