scrolltop 停止在目标位置上方 50px

scrolltop stop 50px above target position

如何修改我的脚本,使其在我的目标上方 50 像素处停止 DIV。这是因为我在屏幕顶部有一个 50 像素宽的固定导航栏,希望将其考虑在内。

$(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: $(hash).offset().top - 50;

其中 50 是您的身高 header。相反,您也可以使用

scrollTop: $(hash).offset().top - $(navbarSelector).height();