[英]How to create a fixed / sticky sidebar in CSS / JS?
我正在嘗試創建一個包含主要內容區域和側邊欄的網站,類似Stack Overflow上的內容。 目標是當您向下滾動時,側邊欄保持可見。
我見過兩種方法:
position:fixed;
方法沒有。 1,據我所知,當視口小於側邊欄內容時會出現問題所以我想這是不能可靠使用的,我見過的JavaScript腳本通常是動畫的或者通常是“慢”的(你可以看到)每次滾動后都會重新繪制)。
有人能指出一個不會受上述問題影響的JavScript庫/ CSS方法嗎?
編輯 :一個例子是這個頁面, 但側邊欄沒有動畫時粘在頂部,並且當側邊欄高於內容/視口時正確處理情況。
我不喜歡沉重的JS解決方案,所以要問的重要的是 - 首選兼容性。 在IE8 +中,它可以代替
var $window = $(window),
$sidebar = $(sidebar);
$window.on('resize', function(){
$sidebar.height($window.innerHeight());
});
$window.resize();
做這樣的事情(純CSS解決方案):
#sidebar {
position: fixed;
left: 0; /* or right */
top: 0;
bottom: 0;
overflow: auto;
}
當您同時具有頂部和底部/左側和右側值時,框將被拉伸。 ( JSFiddle演示 )
得到它了。 這是基於Javascript的,但我確定沒有什么重,甚至IE8應該解決它很好。
var top = $('#sidebar').offset().top;
var height = $('#sidebar').height();
var winHeight = $(window).height();
var gap = 10;
$(window).scroll(function(event) {
var scrollTop = $(this).scrollTop();
// sidebar reached the (end - viewport height)
if (scrollTop + winHeight >= top + height + gap) {
// if so, fix the sidebar and make sure that offset().top will not give us results which would cancel the fixation
$('#sidebar').addClass('fixed').css('top', winHeight - height - gap + 'px');
} else {
// otherwise remove it
$('#sidebar').removeClass('fixed').css('top', '0px');
}
});
不確定你是否已經弄清楚但我已經創建了一個包含粘性側邊欄jQuery插件。 它非常簡單,只需一行jQuery即可調用。 看看這里: http : //mojotech.github.com/stickymojo/
它從位置開始:固定; 然后使用javascript來處理任何調整大小,滾動甚至允許您指定它不應該相交的頁腳元素。 通過組合這些方法,您將獲得一個平滑的固定元素。 另外,我們為您提供了便利。
您可以捕獲客戶端窗口的高度並將其提供給您的側邊欄,如下所示:
var sidebarHeight = $(window).innerHeight();
$('#sidebar').css('height',sidebarHeight);
使用側邊欄的正確CSS:
#sidebar {
position: fixed;
right: 0;
top: 0;
width: 200px;
overflow: hidden;
}
您還可以注意調整窗口大小以避免調整大小的混亂:) 以下是使用jQuery的方法
祝好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.