我有一个侧边栏,它的位置是通过JS设置的。基本上,当页面滚动时,它必须保持在原位,但是,当它到达容器的末尾时,它会关闭。如何保留(固定的)div 以免它离开容器?我将在此处发布代码和图像,以更好地解释我在说什么。
示例:http://www.cosmosgraphicdesign.com/portfolio/work.html?featured
标记:
<div class="container">
<div id="sidebar">
<!-- Sidebar Content -->
</div>
<div id="mainContent">
<!-- Main Content -->
</div>
</div>
.CSS:
#sidebar{
position: absolute;
width: 350px;
padding-left: 10px;
}
JQuery:
var mainContent;
var navbarHeight = $(".navbar").height();
var sidebarHeight = $("#sidebar").height()/2;
$(document).on( "scroll", function(){
mainContent = $(".work").scrollTop() + navbarHeight;
$("#sidebar").css("top", mainContent);
if(mainContent => $(".work").height()){
mainContent = $(".work").scrollTop() + navbarHeight - sidebarHeight;
$("#sidebar").css("top", mainContent);
}
});
这就是我想解释的: 图像离开容器
如果我正确理解问题,这是我所做的原始示例:
var mainContentHeight = $("#mainContent").height();
var mainContentTop = $("#mainContent").offset().top;
var sidebarHeight = $("#sidebar").height();
var sidebar = $("#sidebar");
$(document).on("scroll", function() {
//'stick' sidebar to the bottom of main block if we scroll 'too far'
if ($(window).scrollTop() + sidebarHeight > mainContentHeight + mainContentTop) {
sidebar.css({
position: 'absolute',
top: mainContentHeight - sidebarHeight + mainContentTop
});
}
//'stick' sidebar to the top of main block
else if ($(window).scrollTop() < mainContentTop) {
sidebar.css({
position: 'absolute',
top: mainContentTop
});
}
//fixed sidebar until it won't reach top or bottom of the main content block
else {
sidebar.css({
position: 'fixed',
top: 0
});
}
});
例