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

时间:2016-06-17 12:49:07

标签: javascript jquery scroll anchor-scroll

我使用以下代码为我的网站上的锚添加平滑滚动。 因为我有一个粘性标题ID,可以通过说200px

来抵消它
$('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;
        }
    }
});

2 个答案:

答案 0 :(得分:3)

尝试在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;
        }
    }
});

答案 1 :(得分:0)

一个没有哈希的简单示例是:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top + -200
    }, 1000);
});
相关问题