Home > Web Front-end > JS Tutorial > body text

The scrolltop method in JS that is perfectly compatible with major browsers_javascript skills

WBOY
Release: 2016-05-16 16:03:10
Original
1142 people have browsed it

1. Differences in scrollTop between browsers

IE6/7/8/9/10:

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 quite special, it has its own function to get scrollTop: window.pageYOffset;

Firefox:

Firefox and other relatively standard browsers are much easier to worry about. Just use document.documentElement.scrollTop;

2. Get the scrollTop value

Perfectly obtain scrollTop assignment phrase:

Copy code The code is as follows:

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

The scrollTop value can be obtained under any circumstances through this assignment.

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

Because when the number 0 is ORed with undefine, the system returns the last value by default. That is, 0 == undefine in OR operation;

When the page scroll bar is just at the top, that is, when the scrollTop value is 0, window.pageYOffset (Safari) under IE returns to undefine. At this time, when window.pageYOffset (Safari) is placed at the end of the OR operation, scrollTop returns undefine, if undefine is used in the next operation, an error will be reported.

Other browsers will not return undefine regardless of scrollTop assignment or order of operations. It can be used safely..

So in the end it’s still IE’s problem. Damn...

I'm a little confused, I don't know if I can express myself clearly.
But in the end, I concluded that this sentence has been tested and is OK, so you can use it with confidence.

Copy code The code is as follows:

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

This is the perfect assignment statement to get scrollTop.

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template