由于 header,scrollto 偏移量 javascript 出现问题

Problem with scrollto offset javascript because of header

我需要有关此 scrollto 代码片段的帮助。问题是我需要设置一个偏移量来说明我的菜单。如果没有偏移量,我滚动到的 header 就会被埋在菜单下面。在这里亲自看看:https://julyfx.mystagingwebsite.com/stanford-mba-msx-essay-topic-analysis-examples/ 有人会碰巧有建议吗? 谢谢!利亚

<script type="text/javascript">
jQuery(document).ready(function($) {
   

$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
});
</script>

只是一个建议,您是否尝试过类似的方法:

window.scrollTo({top: (jQuery('#2').position().top-jQuery('header').height()), behavior: 'smooth' })

?

#2 将从您上面的 this.hash 目标中提取?

应该相对容易:如果你的 header 是例如 85px 高,你可以将这些 85px 添加到代码中的偏移量,所以这一行

scrollTop: target.offset().top

变成

scrollTop: target.offset().top - 85

这样 window 将比计算的滚动少 85 像素,因此该部分不会隐藏在 header 之后。