JS is perfectly compatible with the scrolltop method of all major browsers

  • 2020-05-30 19:23:36
  • OfStack

1. Differences of scrollTop in different browsers

IE6 7/8/9/10:

document.body.scrollTop can be used to get scrollTop height for pages without doctype declaration.
For pages with an doctype declaration, you can use document.documentElement.scrollTop;

Safari:

safari is special in that it has its own function to get scrollTop: window.pageYOffset;

Firefox:

Firefox and other standard browsers are much easier to use, using document.documentElement.scrollTop;

2. Get the scrollTop value

Get the scrollTop assignment phrase perfectly:


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

The scrollTop value can be obtained in any case by this assignment.

Look closely at this assignment. Do you see anything?
That's right, window.pageYOffset (Safari) is placed in the middle of |, |.

Because when the number 0 is or evaluated with undefine, the system returns the last value by default. Zero == undefine;

When the scrollbar is right at the top, scrollTop is 0, IE window.pageYOffset (Safari) returns undefine, and window.pageYOffset (Safari) is placed at the end of the or operation. scrollTop returns undefine, and undefine returns an error for the following operation.

Other browsers will not return undefine no matter what the assignment or order of operation is. It is safe to use..

So it's all about IE.

The spirit is a bit absentminded, do not know whether to express clearly.
But in the end, we can conclude that OK has been used in this experiment, so you can use it safely.


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

This is the perfect get scrollTop assignment statement.

That's all for this article, I hope you enjoy it.


Related articles: