1. Differences in scrollTop under different browsers
IE6/7/8:
For pages without doctype declaration, you can use document.body.scrollTop to get the scrollTop height ;
for pages with doctype declaration, you can use document.documentElement.scrollTop;
Safari :
safari is special, it has its own function to get scrollTop: window.pageYOffset ;
Firefox:
Firefox and other relatively standard browsers are more worry-free, just use document.documentElement.scrollTop directly;
2. Get scrollTop value
perfectly to get scrollTop Assignment phrase:
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
With this assignment, the scrollTop value can be obtained in any case.
Carefully observe this assignment, do you find anything? ?
That's right, window.pageYOffset (Safari) is placed in the middle of ||.
Because when the number 0 is ORed with undefined , the system returns the last value by default. That is, 0 == undefined in the OR operation;
when the page scroll bar is just at the top, that is, when the scrollTop value is 0. Under IE, window.pageYOffset (Safari) returns as undefined, and when window.pageYOffset (Safari) is placed at the end of the OR operation, scrollTop returns undefined, and if undefined is used in the next operation, an error will be reported.
And other browsers will not return undefined regardless of scrollTop assignment or order of operations. It can be used safely.
So it's still IE's problem at the end of the day
.
But in the end, I concluded that the experiment is OK, and everyone can use it with confidence;
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;