简体   繁体   中英

scrollTop offset for anchor links not working when clicking from a different page

I have a header on my site with a fixed position, sticking to the top of the screen as a user scrolls down. The site's navigation includes two anchor links that scroll down to the appropriate section on the homepage, and then one link to a different page (a blog). This is the code I am using for the smooth scrolling of the anchor links:

$(function() {
  $('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top - $('header').height()
        }, 600);
        return false;
      }
    }
  });
});

Everything works great on the homepage. The problem I'm having is when you click one of the two anchor links for the homepage when you're on the blog page. It goes where it's supposed to go on the home page, technically, except it's not offsetting the position by the header's height like it does when you're already on the home page.

I'm not good with javascript at all. I found this code online (and received some help for the offset on this site). I'm really trying but it's just not clicking yet. Why is this happening and how can I fix it?

Your problem is that the code you have is only for click events . So therefor when you load a page with an anchor in the url the scroll to event isn't being triggered.

You need an additional bit of code that only triggers on page load.

$(document).ready(function() { 
  var elem = $('#_' + window.location.hash.replace('#', ''));
  if (elem) {
    $.scrollTo(elem.left, elem.top);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM