问题
I would like to know it would be possible to create a sort of altimeter / counter display that dyamically changes the counter as you scroll.
For example when you are in the top of the page it displays 10 000 and as you scroll down it decreases, until it reaches to 0 when you have scrolled to the bottom of the page.
It should work according to the scrolling, so when you scroll up it increases and scroll down decreases, with a max range of lets say, 10000 in the top of the page and 0 in the bottom.
Is ther a simple function that solves this?
回答1:
I hate "gimme-codez" questions, but this is actually pretty straightforward, once you figure out all the math involved. The key function is scrollTop(), which gets the current scroll position in pixels, which you retrieve every time the scroll is triggered:
$(document).on('scroll',function(e) {
var maxcount = 10000,
scrollpos = $(document).scrollTop(),
maxpos = $(document).height() - $(window).height(), // might be zero!
counter = Math.round((maxpos-scrollpos)*(maxcount/maxpos)) || 0;
// (maxpos-scrollpos) counts backwards, while
// (maxcount/maxpos) scales the result to a number
// between 0 and maxcount
$('#counter').text(counter);
});
$(document).trigger('scroll'); // run at once
http://jsfiddle.net/mblase75/8MfzX/
If the page is too short to scroll, the counter will remain at zero. If you want the counter to be maxcount
in this case, just say so:
maxpos = $(document).height()-$(window).height() || maxcount,
http://jsfiddle.net/mblase75/8MfzX/9/
来源:https://stackoverflow.com/questions/15579683/jquery-height-altimeter