由于标题

时间:2018-10-27 22:18:53

标签: javascript jquery scrollto

我需要有关此scrollto代码段的帮助。问题是我需要为菜单设置一个偏移量。没有偏移量,我滚动到的标题将隐藏在菜单下方。自行查看: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>

2 个答案:

答案 0 :(得分:1)

应该相对容易:如果标头的高度例如为85px,则可以将这些85px添加到代码的偏移量中,因此此行

scrollTop: target.offset().top

成为

scrollTop: target.offset().top - 85

这样,窗口将比计算的滚动少85px,因此该部分不会隐藏在标题后面。

答案 1 :(得分:0)

只是建议您尝试过类似的事情:

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

将从上面的this.hash目标中获取第二个位置?

相关问题