开发者

Is it possible to find distance from bottom to current scroll state in jquery

Suppose have scrolled down to the middle of a web page.

Is it possible to find the distance, in length or pixels, from the bottom?

Like when scroll-bar hits the bottom then its 0 开发者_如何学Gobut if it 500px from the bottom then I need that 500px value.


It's not so precise but works:

var scrollPosition = window.pageYOffset;
var windowSize     = window.innerHeight;
var bodyHeight     = document.body.offsetHeight;

alert(Math.max(bodyHeight - (scrollPosition + windowSize), 0));


Also try this:

$(document).height() - ($('body').height() + $('body').scrollTop())


Tweaking rkleine's answer. I found it was actually, this:

$(document).height() - ($(window).height() + $('body').scrollTop())

i.e. $(window) for the height not $('body')


Here is the code in vanilla JS:

var distanceFromBottom = document.body.scrollHeight - window.innerHeight - window.scrollY


var distanceFromBottom = $(document).height() - $(window).height() - $(document).scrollTop();


I had to further tweak previous answers to make it work:

distFromBottom = $(document).height() - $(window).scrollTop() - $(window).height();

Just to break it down:

let bottomToWinTop = $(document).height() - $(window).scrollTop();

This gets the distance from the bottom of document to the top of the window. Since window height will vary, subtract the current window height to get the offset from the bottom

let bottomToWinBottom = bottomToWinTop - $(window).height();

Now bottomToWinBottom = distFromBottom = 0 when user is scrolled completely down the page and as they scroll up, it's value is the distance below the window which makes for a good indicator of vertical positioning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜