2017-08-15 96 views
0

我想爲頁面上的定位點使用平滑滾動。 因此,我使用以下代碼:錨定慢速滾動固定標題

<script> 
$(document).on('click', 'a', function(event){ 
    event.preventDefault(); 

    $('html, body').animate({ 
     scrollTop: $($.attr(this, 'href')).offset().top 
    }, 500); 
}); 
</script> 

唯一的問題是,我有一個固定報頭,與88px的高度。所以當點擊錨點時,它目前滾動到很遠。

如何擴展我的代碼以使其正常工作?

回答

2

如果你知道你的固定頭將總是有88px的高度,你可以簡單地認爲價值加入到最終的滾動位置,以騰出空間爲:)

$('html, body').animate({ 
    scrollTop: $($.attr(this, 'href')).offset().top + 88 
}, 500); 

如果固定頭高度可能會發生變化,您需要檢查它是否爲outerHeight並將其添加到偏移量。假設固定頭的jQuery對象存儲爲$fixedHeader

$('html, body').animate({ 
    scrollTop: $($.attr(this, 'href')).offset().top + $fixedHeader.outerHeight() 
}, 500); 
0

你嘗試88px添加到scrollTop的?

<script> 
$(document).on('click', 'a', function(event){ 
    event.preventDefault(); 

    $('html, body').animate({ 
     scrollTop: $($.attr(this, 'href')).offset().top + 88; 
    }, 500); 
}); 
</script>