Href 滚动到带有偏移量的页面

Href scroll to page with offset

本文关键字:偏移量 滚动 Href      更新时间:2023-09-26

如何使页面滚动到我的ID我正在使用下面的代码使页面滚动到我想要的位置,但它仅在页面加载时触发

$('html,body').animate({
    scrollTop: $(id).offset().top - 64
}, 'slow');

在可单击的链接上,仅

 href="page#a" 

被使用。这会滚动到div,但不会滚动到我想要的地方。有没有办法让我也可以在 href 上偏移 64 像素?谢谢

id的css如下:

#a, #b {
    margin-bottom: 64 px;
    visibility: hidden;
    position: absolute;
    left: -999em;
}
       var top_val = $('.test');
        $('html, body').stop().animate({
            scrollTop: top_val.offset().top
        }, 'slow');
  $(document).ready(function() {
      function scroll (id) {
        $(id).bind('click', function(event) {
            event.preventDefault();
            var $anchor = $(this).attr('href');
            $('html, body').stop().animate({
                scrollTop: ($anchor).offset().top - 64
            }, 'slow');
        });
      }
      scroll('#page1');
      scroll('#page2');
    });    
    <a href="" id="page1" >Visit W3Schools</a>
    <a href="" id="page2" >Visit W3Schools</a>