jQuery:如何在scrollTop中添加额外的像素

7

我正在使用以下代码来平滑移动,当用户点击一个以“#”开头的 href 链接时:

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

我需要将scrollTop值增加约40px,以便停止点不覆盖内容。我修改了代码如下,但似乎并没有实现(注意代码末尾的+40):

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

你在正确的位置添加了 + 40。这是什么意思? - Praveen Kumar Purushothaman
我刚刚把那个40添加回来,请看一下。无论我加入什么值,它都会停在同一个位置。 - farjam
你是否验证了$target.offset().top返回了预期值? - George Cummins
2个回答

22

虽然我回答晚了,但是需要解决问题的人可以尝试这个方法。

将 .top + (-40) 添加进去就可以解决问题了。

$('html, body').stop().animate({
    'scrollTop': $target.offset().top + (-40)
}, 900, 'swing', function () {
    window.location.hash = target;
});

这是一种更好的解决方案,不会涉及到 CSS 类切换。 - Arthur Samarcos
1
这对我不起作用,一旦平滑动画完成到一个元素,它会在最后做出额外的回弹。 - ints

3

您实际想要为+40的偏移量变成-40,但是这不起作用,因为一旦动画完成,浏览器会执行其默认反应,即跳转到传递给window.location.hashid元素。

您可以删除该行或将以下 CSS 添加到要滚动到的元素中。

padding-top: 40px;
margin-top: -40px;

请查看FIDDLE

谢谢,我按照您的建议调整了我的js代码,将一个名为“targeted”的类添加到我的目标元素中。然而,尽管我可以调整“.targeted” div的css样式,但如果用户开始垂直滚动页面,页面看起来仍然不太对劲,因为他们会看到由我的css添加的间隙。希望我表达清楚了。 - farjam
你的代码中 window.location.hash = target; 这行是否对其他功能至关重要? - Blake Plumb
不是的。它可以被移除。 - farjam
3
那么,我会删除那一行代码,只要你将偏移量改为“-40”,你的代码就如预期般能够工作。祝你好运! - Blake Plumb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接