设置滚动到元素时距页面顶部的像素距离



我使用下面的jQuery代码从顶部的固定导航栏在页面上的元素之间滚动,该导航栏运行良好,可以接受顶部的一些文本消失在导航栏后面。我如何修改这个代码,使它只滚动到离页面顶部(导航栏的高度)特定的距离?

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();
    var target = this.hash;
    var $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

如果您不想一直滚动到顶部,您可以简单地将所需的偏移添加到scrollTop

var height = //<distance to top>;
$('html, body').stop().animate({
    'scrollTop': $target.offset().top + height
}, 900, 'swing', function () {
    window.location.hash = target;
});

最新更新