带有偏移量的 Jquery 平滑滚动

问题描述

我有以下代码可以在我的网站上平滑滚动。现在,当我单击以移至新部分时,它会切断该部分的标题。我看过其他显示偏移的 jquery 示例,但我想修改代码,因为它现在不在我的网站上工作。

$(document).ready(function () {
    $("a").on("click",function (event) {
        if (this.hash !== "") {
            event.preventDefault();

            var hash = this.hash;

            $("html,body").animate(
                {
                    scrollTop: $(hash).offset().top,},800,function () {
                    window.location.hash = hash;
                }
            );
        }
    });
});

解决方法

当您将某个部分的顶部设置为 scrollTop 时,它会像这样滚动直到该部分位于视口的开头。

Section without header

但正如您所记得的,您的网站顶部有一个粘性标题。因此,需要通过从该部分的顶部删除该空间来保留该空间。

$(document).ready(function () {
    $("a").on("click",function (event) {
        if (this.hash !== "") {
            event.preventDefault();

            var hash = this.hash;

            $("html,body").animate(
                {
                    scrollTop: $(hash).offset().top - 109,// section's top - header's height
                },800,function () {
                    window.location.hash = hash;
                }
            );
        }
    });
});

如果您需要进一步的支持,请告诉我。