[英]jQuery scroll function: offset by height of fixed header
我正在使用以下jQuery click函數跳轉到長滾動頁面的各個部分(通過錨點ID),這些部分也將固定導航標頭的高度考慮在內,並因此偏移了:
$('#nav a').click(function(){
var el = $(this).attr('href');
var elWrapped = $(el);
scrollToDiv(elWrapped,75);
return false;
});
function scrollToDiv(element,navheight){
var offset = element.offset();
var offsetTop = offset.top;
var totalScroll = offsetTop-navheight;
$('body,html').animate({
scrollTop: totalScroll
}, 500);
}
這種方法效果很好,但是,這種方法的唯一缺點是,我必須定義一個偏移量,以使滾動距頁面頂部偏移-在這種情況下,偏移量為75px,即固定標題的高度。 對於固定標頭的高度可能會發生變化的情況(例如,通過媒體查詢進行移動),此高度可能不准確,鏈接也不會偏移正確的空間量。
因此,我想知道如何通過計算標頭的實際高度和偏移該量, 再加上 10個額外的像素來說明部分填充,來更改/增強此功能。
感謝您的協助。
單擊按鈕時,可以獲得標題的高度。
$('#nav a').click(function(){
var el = $(this).attr('href');
var elWrapped = $(el);
var header_height = $('#header-id-goes-here').height() + 10;
//var header_height = $('#header-id-goes-here').outerHeight(); You might need outerHeight if you have padding and borders
scrollToDiv(elWrapped,header_height);
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.