JS implements a method to determine if a scroll bar has been rolled to the bottom of the page and an event has been executed

  • 2020-05-07 19:15:48
  • OfStack

You need to know three dom elements: clientHeight, offsetHeight, scrollTop.

clientHeight: the height of this element, the height that takes up the entire space, so if an div has a scroll bar, that height does not include the contents of the part below that the scroll bar does not show. It's just the height of the pure DIV.

offsetHeight: refers to the height of the element content. According to the above, this height is the height inside DIV, including the visible part and the invisible part under the scrollbar.

scrollTop: what is this? It can be interpreted as the length of the scroll bar.

For example, if an DIV height is 400px (i.e. clientHeight is 400), and the content inside is a very long list, the content height is 1000px (i.e. offsetHeight is 1000). So, the visible part we see that 400px, 1000px and 600px are not visible. And the part that's not visible, it's the part that we can display by pulling on the scroll bar. If you don't pull the scroll bar, scrollTop is 0, and if you pull the scroll bar down to the bottom of the list, scrollTop is 600. So the value range of scrollTop is [0, 600]. So this 600 can be interpreted as the length that the scroll bar can scroll.

After understanding the concept above. It's easy to see if you can scroll to the bottom.

First, we pull the scroll bar from the top to the bottom, changing the value of scrollTop, which has an interval.
The interval is: [0, (offsetHeight-clientHeight)]
That is, the entire process of scroll bar pulling varies from 0 to (offsetHeight and clientHeight).

1. Scroll to the bottom of the scroll bar: scrollTop == (offsetHeight wudclientHeight)
2. Within 50px of the bottom of the scroll bar: (offsetHeight, WCS 49en) WCS 50en < = 50
3. Within 5% of the bottom of the scroll bar: scrollTop/(offsetHeight, clientHeight) > = 0.95

As above.

If you want to implement pull down to the bottom automatically load content. Just register a scrollbar event:


scrollBottomTest =function(){
     $("#contain").scroll(function(){
         var $this =$(this),
         viewH =$(this).height(),// Highly visible
         contentH =$(this).get(0).scrollHeight,// Content high
         scrollTop =$(this).scrollTop();// Scroll to height
        //if(contentH - viewH - scrollTop <= 100) { // Reach the bottom 100px when , Loading new content
        if(scrollTop/(contentH -viewH)>=0.95){ // Reach the bottom 100px when , Loading new content
        // I'm loading the data ..
        }
     });
}

PS: here we recommend an online inquiry tool about JS events, summarized the JS commonly used event types and functions:

javascript event and function description:

http://tools.ofstack.com/table/javascript_event


Related articles: