固定/跟随边栏的问题 [英] Problem with fixed/following sidebar
问题描述
我正在尝试创建一个侧边栏,当用户向下滚动页面时,我会使用以下代码完成效果:
I'm trying to create a sidebar which follows the user when he scrolls down the page and I managed to accomplish the effect using the following code:
标记
<div id="contentWrapper">
<div id="lcWrapper">
<div class="editor_left" id="leftColumn" data-id="">
</div>
</div>
<!-- other divs (central and right column) -->
<div style="clear: both;"></div>
</div>
Javascript
var $sidebar = $("#leftColumn"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 15;
$window.scroll(function() {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
}, 300);
} else {
$sidebar.stop().animate({
marginTop: 0
}, 300);
}
});
它工作正常,但我还是有一个问题:当我向下滚动页面时,侧边栏应该停止跟踪我,如果我到达页面的结尾;这个代码发生了什么,当我到达页面的末尾,而不是停止边栏进一步向下移动,它的容器被拉伸(它的高度增加),我可以继续向下滚动尽可能多的我想要的我不能到达页面的末尾,因为当向下滚动时总是添加一些额外的空间)。
It works just fine but I still have a problem: when I scroll down through the page, the sidebar should stop following me if I've reached the end of the page; what happens with this code is that instead of just stopping the sidebar from moving further down when I reach the end of the page, its container gets "stretched" (its height increases) and I can continue scrolling down as much as I want (actually I can't pratically reach the end of the page since some extra space gets always added when I scroll down).
我希望你得到的问题,我不知道我是否已经足够清楚了。我知道这可以通过检查滚动事件处理程序中的列的位置和高度来解决,但我希望有一个简单的解决方案使用CSS设置?
I hope you get the problem, I don't know if I've been clear enough. I know this could be solved by doing a check on the position and height of the column in the scroll event handler, but I hoped there was a simple solution using CSS settings?
任何帮助?
推荐答案
如果你绝对放置边栏(位置:绝对)和容器(最接近的父,#lcWrapper和/或#contentWrapper)有位置:相对)有默认溢出(溢出:静态)容器大小不应该改变,侧边栏应该保持可见。在这种情况下,你将动画CSS顶部属性(如top:300px)。
If you position the sidebar absolutely (position:absolute), and the container (closest parent, #lcWrapper and/or #contentWrapper) that has position:relative) has default overflow (overflow:static) the container size shouldn't change and the sidebar should stay visible. In this case you'd animate the CSS top-property (like top:300px).
在这种情况下CSS应该是
In this case CSS should be something like
#contentWrapper {position:relative;}
#leftColumn {position:absolute; top: 100px;}
这篇关于固定/跟随边栏的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!