我正在研究(粘性)滚动侧边栏。问题是大多数粘性侧边栏没有考虑到侧边栏可以比视口(viewport)高(例如,如果许多项目被添加到篮子(侧边栏))。这就是我要解决的问题。这些是要求:
如果侧边栏的高度比视口(viewport)高,它应该 滚动浏览内容,div 的底部应该坚持 向下滚动时视口(viewport)底部。
如果侧边栏的高度比视口(viewport)高,则 div 仅当您位于底部时才应显示下方 页面。
当用户向上滚动时,侧边栏会滚动回到顶部, 粘回到视口(viewport)的顶部。
如果侧边栏的高度小于视口(viewport),它应该是 向下滚动时从顶部开始粘。
所以总而言之,有相当多的功能,但并不那么简单(我认为)。我所看到的最接近我想要实现的是这个例子: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);
});
}
});
最佳答案
您正在使用边距来移动粘性侧边栏 - 我发现这是处理当前请求的一种棘手方法(并且可能是一种更重的方法)。
一般来说,我喜欢简单地向侧边栏添加一个类,使其成为“位置:固定”,这样浏览器就可以完成保持锁定的繁重工作。
对于您当前的要求,您只需根据向下滚动的距离以编程方式滚动固定位置的 div(高度也设为 100%)。看看我的例子,看看这是否是您想要的效果:http://jsfiddle.net/ZHP52/1/
这是 jquery:
jQuery(document).ready(function($) {
var $sidebar = $('.sidebar'),
$content = $('.content');
//Since our CSS is going to monkey with the height as you scroll, I need to know the initial height.
var sidebarHeight = $sidebar.height();
if ($sidebar.length > 0 && $content.length > 0) {
var $window = $(window),
offset = $sidebar.offset(),
timer;
$window.scroll(function() {
if ($content.height() > sidebarHeight) {
var new_margin = $window.scrollTop() - offset.top;
if ($window.scrollTop() > offset.top) {
// Fix sidebar
$sidebar.addClass("fixed");
// Scroll it the appropriate ammount
$sidebar.scrollTop(new_margin);
}else{
$sidebar.removeClass("fixed");
}
}
});
}
});
关于javascript - 高级 jQuery 粘性侧边栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15624834/