[英]Sticky Sidebar that only sticks when sidebar bottom is at window bottom
我有2列的布局。 左列比邊欄更長。 我只希望邊欄在底部到達瀏覽器窗口底部時才粘住。 因此,用戶可以在滾動右側欄的同時繼續向下滾動左列的內容。 我在這里看到了很多棘手的問題,但是這種特殊情況仍然讓我感到困惑。 我在左列上也有一個粘貼的標題欄,我已經成功粘貼了。
快速瀏覽一下我正在嘗試的js。
$(function(){
var headlineBarPos = $('.headlineBar').offset().top; // returns number
var sidebarHeight = $('.sticky-sidebar-wrap').height();
var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
var windowHeight = $(window).height();
var totalHeight = sidebarHeight + sidebarTop;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
// fixing the headline bar
if (headlineBarPos < windowTop) {
$('.headlineBar').addClass('sticky').css('top', '0');
}
else {
$('.headlineBar').removeClass('sticky').removeAttr('style');
}
if(sidebarHeight < windowTop) {
$('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
} else {
$('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style');
}
console.log(windowTop);
});
console.log(headlineBarPos);
console.log(sidebarHeight);
console.log(sidebarTop);
});
我希望我做對了,當側邊欄的底部進入視圖時,該堅持了嗎?
我在側邊欄底部(在側邊欄內)創建了另一個div。 當看到它時,它會黏附。
<div class="moduleController"></div> //inside the sidebar
和在js中
$(function () {
var headlineBarPos = $('.headlineBar').offset().top; // returns number
var moduleControllerPos = $('.moduleController').offset().top; // returns number
var sidebarHeight = $('.sticky-sidebar-wrap').height();
var sidebarTop = $('.sticky-sidebar-wrap').offset().top;
var windowHeight = $(window).height();
var totalHeight = sidebarHeight + sidebarTop;
$(window).scroll(function () { // scroll event
var windowTop = $(window).scrollTop(); // returns number
// fixing the headline bar
if (headlineBarPos < windowTop) {
$('.headlineBar').addClass('sticky').css('top', '0');
} else {
$('.headlineBar').removeClass('sticky').removeAttr('style');
}
if (moduleControllerPos < windowTop + windowHeight) {
$('.sticky-sidebar-wrap').addClass('sticky').css('top', '0');
} else {
$('.sticky-sidebar-wrap').removeClass('sticky').removeAttr('style'); }
console.log(windowTop);
});
console.log(headlineBarPos);
console.log(sidebarHeight);
console.log(sidebarTop);
});
希望對您有所幫助。
就像是:
if (sidebar.top + sidebar.height < window.scrolltop + window.height) {
// set sticky
}
並設置粘性需要考慮到側邊欄可能高於視口,因此:
sidebar.top = sidebar.height - window.height // this will be a negative number
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.