简体   繁体   中英

Scroll to div ID with offset

I am currently runnning a test site on Wordpress. I have my page with several divs which have IDs and a menu on top with anchors which lead to those IDs. My header is sticky, so when I click an anchor, it navigates to the div ID, but the beginning of the div stays hidden below the header. I would like it so that when I click an anchor, it navigates to the div, but few pixels above it. I managed to do that, though with a little problem.

(function($,document){
  $("a[href^='#']").click(function(){
    var url = $(this).attr('href');
    $('html,body').animate({scrollTop: $(url).offset().top - 90}, 2000);
  });
})(jQuery);

What happens is:

  1. I click an anchor with a href="#someid"
  2. My browser navigates to the #someid with offset of - 90px (It works perfectly so far)
  3. Then my browser scrolls 90px down, to the position where the div #someid starts at the beginning of the viewport (and behind the sticky header).
  4. Finally my URL changes to http://example.com/#someid

I just want to delete step 3. Any help is much appreciated.

Update: I just found out my theme has jQuery "One-page-nav" plugin installed and it is interfering. Still trying to understand how it works and if I can modify it to have offsets

I was having the same issue and in my case I solved it by adding padding-top and a negative margin-top of the same value:

.some-class {
  padding-top: 4em;
  margin-top: -4em;
}

By doing this my element looks like it's on the exact same location but the browser finds it sooner while scrolling. You can set these values to the height of your sticky header or play around to make sure the heading is exactly where you want it to be.

I hope I'm explaining this in a way that's understandable... It sure makes sense in my head :D

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