当“侧边栏”到达“固定标题”而不是页面顶部时,如何使“侧边栏”固定位置?
$(function() {
var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
var footTop = $('#footer').offset().top - parseFloat($('#footer').css('marginTop').replace(/auto/, 0));
var maxY = footTop - $('#sidebar').outerHeight();
$(window).scroll(function(evt) {
var y = $(this).scrollTop();
if (y > top) {
if (y < maxY) {
$('#sidebar').addClass('fixed').removeAttr('style');
} else {
$('#sidebar').removeClass('fixed').css({
position: 'absolute',
top: (maxY - top) + 'px'
});
}
} else {
$('#sidebar').removeClass('fixed');
}
});
});
最佳答案
这一行:
if (y > top) {
假设您的固定标题没有填充(否则您也必须考虑到这一点)您可以更改为此
if (y >= top - $('#fixedHeader').height()) {
从你的侧边栏 css 中删除 top:0px;
,并为你的固定标题添加预期的高度(目前你给它的高度是 40px),所以
#sidebar.fixed {
position: fixed;
top: 40px;
}
我还从你的 #fixedHeader
中删除了填充,因为你没有指定它是什么/如果你想要的话。如果您确实需要填充,如上所述,您也必须将其添加到您的计算中。
关于jquery - div位置固定在滚动条上,在页面顶部之前开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21830736/