[英]Anchor slow scroll fixed header
我想為頁面上的錨點使用平滑滾動。 因此我使用以下代碼:
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
</script>
唯一的問題是我有一個固定的標題,高度為 88px。 所以當點擊錨點時,它當前滾動到很遠。
如何擴展我的代碼以使其正常工作?
如果您知道固定標題的高度始終為 88 像素,則只需將該值添加到最終滾動位置即可為該位置騰出空間:)
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + 88
}, 500);
如果固定標題高度可能會改變,您將需要檢查它的外層高度並將其添加到偏移量中。 假設固定標頭的 jQuery 對象存儲為$fixedHeader
:
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + $fixedHeader.outerHeight()
}, 500);
您是否嘗試將 88px 添加到 scrollTop ?
<script>
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top + 88;
}, 500);
});
</script>
僅 CSS 解決方案
html{
scroll-behavior: smooth;
}
[id] { scroll-margin-top: 88px }
此 css 將滾動行為設置為平滑,並將頁面上的所有錨點設置為具有 scroll-margin-top 屬性,該屬性將滾動捕捉到設置的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.