5

我使用以下代码在我的网站上为锚点添加平滑滚动。因为我有一个粘性标题 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;
        }
    }
});
4

2 回答 2

11

尝试在 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;
        }
    }
});
于 2016-06-17T13:43:30.453 回答
3

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

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top + -200
    }, 1000);
});
于 2019-07-16T15:20:02.507 回答