Calculate how much user has scrolled (incl margins

2019-08-27 21:44发布

问题:

I'm stuck with a very annoying problem. I'm trying to create a script that changes the menu bar (CSS) when the user has X pixels scrolled (height of header element). However, any jQuery script I've tried doesn't calculates the scrolled distance correctly. After some pixels it stops counting, and continues.. and then resumes, stops, resumes, etc.

I think it may have something to do with padding and/or margins.. Anyway, I need some support.

Check out the current site, with a 'distance scrolled' script appended.

Script:

$(window).scroll(function() {
  var scrollTop = $(window).scrollTop();
  console.log(scrollTop);
});

回答1:

You've got two scrollbars going for a start. Add overflow: inherit; to your body's css to solve this.

DEMO

This should do roughly what you want. At 120px scrolled down, a header slides down overtop the content.

If this doesn't help, please describe exactly what you're trying to achieve a little better.