Yun*_*ork 10 html javascript jquery sidebar sticky
我正在使用(粘性)滚动侧边栏.问题是大多数粘性侧边栏没有考虑边栏可能比视口高(例如,如果很多项目被添加到篮子(侧边栏)).这就是我想要解决的问题.这些是要求:
如果侧边栏的高度比视口高,则应滚动内容,并且当向下滚动时,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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
您正在使用边距来移动粘性侧边栏 - 我发现这是处理您当前请求的一种棘手方法(并且可能是一种更重的方法)。
一般来说,我喜欢简单地向侧边栏添加一个类,使其成为“位置:固定”,这样浏览器就可以完成保持其锁定的繁重工作。
对于您当前的要求,您只需根据它们向下滚动的距离以编程方式滚动该位置固定 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");
}
}
});
}
});
Run Code Online (Sandbox Code Playgroud)