jQuery Height Altimeter

拟墨画扇 提交于 2021-01-28 19:27:19

问题


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

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