最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Meaning of $(window).scrollTop() == $(document).height() - $(window).height() - Stack Overflow

programmeradmin2浏览0评论

The following code is used to detect if a user has scrolled to the bottom of the page and it works.

if($(window).scrollTop() == $(document).height() - $(window).height()){
//do something
}

Problem:

I don't understand why you subtract the height of the window from the height of the document, then compare that to the scroll height to determine whether or not the bottom of the page has been reached. Why isn't it simply

if($(window).scrollTop() == $(document).height()){
//do something
}

or

if($(window).scrollTop() ==  $(window).height()){
//do something
}

The following code is used to detect if a user has scrolled to the bottom of the page and it works.

if($(window).scrollTop() == $(document).height() - $(window).height()){
//do something
}

Problem:

I don't understand why you subtract the height of the window from the height of the document, then compare that to the scroll height to determine whether or not the bottom of the page has been reached. Why isn't it simply

if($(window).scrollTop() == $(document).height()){
//do something
}

or

if($(window).scrollTop() ==  $(window).height()){
//do something
}
Share Improve this question edited Jul 10, 2016 at 10:46 Jonathan Hall 79.6k19 gold badges158 silver badges201 bronze badges asked Mar 28, 2013 at 19:31 Usman MutawakilUsman Mutawakil 5,2599 gold badges49 silver badges85 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

This is because $(window).scrollTop() returns the position of the top of the page, and $(document).height() returns the position of the bottom of the page. Therefore you need to subtract the height of the window to get the position to compare against, as this will give you the position where the top of the page would be if you were fully scrolled to the bottom.

$(window).scrollTop() is the location of the top of the window relative to the document. On the page I'm looking at right now, that's 1385 if I'm scrolled to the very bottom. $(document).height() is the height of the entire page (1991 for me). $(window).height() is the height of the window (viewport) (606 for me). This means that the position of the top of the viewport plus the height of the window is the position of bottom of the viewport. 1385 + 606 = 1991.

The scrollTop value will never be as high as the document height value. That would mean that you scrolled past the document so that it's all outside the window.

Comparing scrollTop to the window height would only mean that you have scrolled one screen down, not to the bottom of the document.

Subtracting the window height from the document height gives you the value where scrollTop will be, when the bottom of the window is at the bottom of the document.

发布评论

评论列表(0)

  1. 暂无评论