到目前为止,我有以下代码:
HTML
#header {
height: 600px;
width: 100%;
background: black;
}
#content {
height: 2000px;
width: 100%;
background: #eeeeee;
}
.sidebar-wrapper {
width: 350px;
height: 350px; /*depends on content*/
background: rgba(0,0,0,0.2);
border-radius: 20px;
padding: 20px;
margin-top: 50px;
}
.session-wrapper {
height: 200px;
width: 100%;
background: #000000;
}
#footer {
width: 100%;
height: 500px;
background: #888;
}
CSS
jQuery(window).scroll(function(e){
var sidebar = jQuery('.sidebar-wrapper');
var sessions = jQuery('.session-wrapper');
var scrollTop = jQuery(window).scrollTop(),
elementOffset = sidebar.offset().top,
distance = (elementOffset - scrollTop),
sessionOffset = sessions.offset().top;
var isPositionFixed = (sidebar.css('position') == 'fixed');
if(distance < 60 && (sessionOffset - elementOffset) > 800 && !isPositionFixed) {
sidebar.css({'position': 'fixed', 'top': '100px', 'width': '350px'});
}
if((sessionOffset - elementOffset) < 800 && isPositionFixed || scrollTop > 1900) {
sidebar.css({'position': 'static', 'top': '0px', 'width': '100%'});
}
});
的jQuery
sidebar-wrapper
基本上,我想要实现的是灰色框(.sessions-wrapper
)向下滚动页面,直到距离{{1}}大约20px,一旦距离为{20}以上我试图让它保持在这个位置,直到你向后滚动它向后滚动的位置,直到它朝向顶部,直到它到达它的原始位置。我想我差不多了,但我需要一些帮助才能让这个工作......
提前致谢!
答案 0 :(得分:2)
您可以使用各种技术对此进行归档。新的position:sticky
属性可以实现类似的结果:
#sidebar-wrapper{
position: -webkit-sticky;
position: -moz-sticky;
position: -o-sticky;
position: -ms-sticky;
position: sticky;
bottom: 0px;
line-height: 30px;
background: gray;
}
见这里:http://jsfiddle.net/4hznD/
但我认为您所看到的与此相似:http://jsfiddle.net/FDv2J/4/(摘自:jQuery scrolling DIV: stop scrolling when DIV reaches footer)
您可以使用类似的代码(您应该对其进行调整):
$(function() {
$.fn.scrollBottom = function() {
return $(document).height() - this.scrollTop() - this.height();
};
var $el = $('#sidebar>div');
var $window = $(window);
$window.bind("scroll resize", function() {
var gap = $window.height() - $el.height() - 10;
var visibleFoot = 172 - $window.scrollBottom();
var scrollTop = $window.scrollTop()
if(scrollTop < 172 + 10){
$el.css({
top: (172 - scrollTop) + "px",
bottom: "auto"
});
}else if (visibleFoot > gap) {
$el.css({
top: "auto",
bottom: visibleFoot + "px"
});
} else {
$el.css({
top: 0,
bottom: "auto"
});
}
});
});
希望它有所帮助!