An in depth analysis of scrollTop in JavaScript

  • 2021-07-02 23:27:25
  • OfStack

Meaning: Scroll bar height

Function: Rolling loading (ajax), rolling navigation fixed positioning, rolling bullet frame positioning and so on.

Shows the effect of scrolling navigation and sidebar scrolling fixed positioning:

1. chrome browser

document. body. scrollTop and document. documentElement. scrollTop are fine

2. Differences of scrollTop under different browsers


For pages without doctype declaration, you can use document. body. scrollTop to obtain scrollTop height;
For pages with doctype declaration, you can use document. documentElement. scrollTop;


safari is quite special, and has its own function to obtain scrollTop: window. pageYOffset;


Firefox and other relatively standard browsers are more worry-free and use them directly

document. documentElement. scrollTop;

3. Get the scrollTop value

Perfect to get scrollTop assignment phrases:

var scrollTop = document.documentElement.scrollTop||window.pageYOffset||document.body.scrollTop;

ps: Problems with the usage of scrolltop in javascript

document. documentElement. scrollTop refers to the vertical coordinates of the scroll bar

document. documentElement. clientHeight refers to the height of the visible area of the browser

document. documentElement. clientHeight-oDiv are the initial vertical coordinates of the floating frame (relative to the top value of body) (this value is fixed)

However, when you pull the scroll bar, the vertical coordinates of the floating box (target) must be increased or decreased based on the initial coordinates to obtain the visual scroll effect with the scroll bar, and this increase or decrease value is the distance that the scroll bar pulls, that is, your scrollTop

Let's tell you the difference between scrollTop and offsetTop in javascript

scrollTop refers to the distance that a scrollable block scrolls down, for example, if it scrolls down 10 pixels, then the scrollTop attribute value of this element is 10;

offsetTop is the absolute distance between the top border of the element and the top border of the parent element.

They do not describe the same thing, so there is no comparability.

Above is the site to introduce the JavaScript in the scrollTop all narration, I hope to help you, if you want to know more content, please pay attention to this site!

Related articles: