具有偏移量的平滑滚动锚点(jquery)

Pah*_*Pow 2 javascript jquery scroll anchor-scroll

我使用以下代码为我的站点上的锚添加平滑滚动。因为我有一个粘性标头ID,想将其偏移200像素

$('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试在scrollTop动画中添加或删除值

$('a[href*="#"]:not([href="#"])').click(function() {
    var offset = -200; // <-- change the value here
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top + offset
            }, 1000);
            return false;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)