【问题标题】:Problem with scrollto offset javascript because of header由于标头而导致滚动偏移javascript的问题
【发布时间】:2019-04-01 06:42:05
【问题描述】:

我需要有关此滚动代码 sn-p 的帮助。问题是我需要为我的菜单设置一个偏移量。如果没有偏移,我滚动到的标题会被隐藏在菜单下方。自己看这里: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>

【问题讨论】:

    标签: javascript jquery scrollto


    【解决方案1】:

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

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

    ?

    #2 会从上面的 this.hash 目标中获取吗?

    【讨论】:

    • 您好 Kummer,感谢您的建议。不幸的是,当涉及到这一切时,我完全不成熟。我认为该解决方案可能与在 target.offset() 周围添加数字偏移量有关。但我不确定。
    • 我明白了。是的,添加数字偏移量就可以了。通过获取 jQuery('header').height() 你可以获得这样一个数字来抵消你的 target.offset().top 。当在移动设备上时,它甚至会考虑标题的高度变化。
    【解决方案2】:

    应该相对简单:如果您的标题例如 85px 高,您可以将这些 85px 添加到代码中的偏移量,所以这一行

    scrollTop: target.offset().top
    

    变成

    scrollTop: target.offset().top - 85
    

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

    【讨论】:

    • 谢谢约翰内斯!你真的帮了我大忙!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2020-08-16
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多