滚动顶部到元素 - 20px

ScrollTop to element - 20px

本文关键字:20px 元素 顶部 滚动      更新时间:2023-09-26

我正在尝试为我的div元素制作一个scrollTop,但不是确切的位置。我要在我的div 元素之前去 20px。我想我可以更好地为您解释显示我的代码:

.HTML:

<div id="arrow-down">Click here and go to content!</div>
<div id="content">The content is here!</div>

JQuery:我已经有一个工作正常的代码,但我想让它与众不同。

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content").offset().top
        }, 800);
    });
});

这段代码将我带到div#content,但我想从顶部转到 20px!

像这样:

$(document).ready(function() {
    $('#arrow-down').click(function() {
        $('html, body').animate({
               scrollTop: $("#content" - 20px).offset().top
        }, 800);
    });
});

好吧,我不知道它看起来是否困惑...希望你们能帮到我!

你可以这样做:

$('html, body').animate({
     scrollTop: $("#content").offset().top - 20
}, 800);
$(document).ready(function() { 
    $('#arrow-down').click(function() {
         $('body').animate({
         scrollTop: $("#content").offset().top-20
    }, 800);
  }); 
});

试试这个