首页 > 解决方案 > 带有偏移量的 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;
                }
            );
        }
    });
});

标签: jquerysmooth-scrolling

解决方案


当您将部分的顶部设置为 时scrollTop,它将滚动直到该部分位于视口的开头,如下所示。

没有标题的部分

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

$(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;
                }
            );
        }
    });
});

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


推荐阅读