[英]div position fixed on the scroll, start before the top of the page
當“側邊欄”到達“固定標題”而不是頁面頂部時,如何將其“固定”定位?
$(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()) {
刪除top:0px;
從你的側邊欄css,並為你的固定標題添加預期的高度(目前你給它的高度為40px),所以
#sidebar.fixed {
position: fixed;
top: 40px;
}
我還從#fixedHeader
刪除了填充,因為你沒有指定它是什么/如果你想要的話。 如果您確實需要填充,如上所述,您還必須將其添加到計算中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.