【发布时间】:2013-03-15 12:37:41
【问题描述】:
我正在开发一个(粘性)滚动侧边栏。问题是大多数粘性侧边栏没有考虑到侧边栏可以比视口高(例如,如果许多项目被添加到篮子(侧边栏))。这就是我要解决的问题。这些是要求:
如果侧边栏的高度高于视口,它应该 滚动浏览内容和 div 的底部应该坚持 向下滚动时视口的底部。
如果侧边栏的高度高于视口,则 div 仅当您位于底部时才应显示下方 页面。
当用户向上滚动时,侧边栏会滚动回顶部并 粘回到视口的顶部。
如果侧边栏的高度小于视口,则应该是 向下滚动时从顶部粘住。
所以总而言之,相当多的功能,而不是那么简单(我认为)。我所看到的最接近我想要实现的是这个例子:http://demo.techbrij.com/730/fix-sidebar-scrolling-jquery.php 但代码的编写方式不适合我的。
到目前为止,这是我所做的:DEMO
还有我使用的 jQuery 代码:
jQuery(document).ready(function($) {
var $sidebar = $('.sidebar'),
$content = $('.content');
if ($sidebar.length > 0 && $content.length > 0) {
var $window = $(window),
offset = $sidebar.offset(),
timer;
$window.scroll(function() {
clearTimeout(timer);
timer = setTimeout(function() {
if ($content.height() > $sidebar.height()) {
var new_margin = $window.scrollTop() - offset.top;
if ($window.scrollTop() > offset.top && ($sidebar.height()+new_margin) <= $content.height()) {
// Following the scroll...
$sidebar.stop().animate({ marginTop: new_margin });
} else if (($sidebar.height()+new_margin) > $content.height()) {
// Reached the bottom...
$sidebar.stop().animate({ marginTop: $content.height()-$sidebar.height() });
} else if ($window.scrollTop() <= offset.top) {
// Initial position...
$sidebar.stop().animate({ marginTop: 0 });
}
}
}, 100);
});
}
});
【问题讨论】:
-
嗯。对于我自己的粘性标题/元素库,我没有考虑到这一点。我想我有一个新问题要解决。 :-) underpull.github.com/Balloon
标签: javascript jquery html sidebar sticky