Problem with scrollto offset javascript because of header

穿精又带淫゛_ 提交于 2019-12-02 04:35:25

问题


I need help with this scrollto code snippet. The problem is that I need to set an offset to account for my menu. Without the offset the header that I scroll to gets buried underneath the menu. See for yourselves here:https://julyfx.mystagingwebsite.com/stanford-mba-msx-essay-topic-analysis-examples/ Would anyone happen to have a suggestion? Thank you! Leah

<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>

回答1:


Should be relatively easy: If your header is for example 85px high, you can just add these 85px to the offset in your code, so this line

scrollTop: target.offset().top

becomes

scrollTop: target.offset().top - 85

that way the window will scroll 85px less than calculated, so the section will not be hidden behind the header.




回答2:


Just a suggestion have you tried something like:

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

?

Where #2 would be taken from your this.hash target above?



来源:https://stackoverflow.com/questions/53026768/problem-with-scrollto-offset-javascript-because-of-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!