The ScrollTop method of JS in the perfect compatibility with each big browser

Source: Internet
Author: User

1, the different browsers under the scrolltop difference

IE6/7/8/9/10:

Document.body.scrollTop can be used to get the scrolltop height for pages without DOCTYPE declarations;
For pages with DOCTYPE declarations, you can use Document.documentElement.scrollTop;

Safari:

Safari is special, has its own to obtain scrolltop function: Window.pageyoffset;

Firefox:

Firefox and so on relatively standard browser is much more worry, directly with Document.documentElement.scrollTop;

2. Get scrolltop Value

Perfect for getting scrolltop assignment phrases:

The

code is as follows:


var scrolltop = Document.documentElement.scrollTop | | Window.pageyoffset | | Document.body.scrollTop;

The value of scrolltop can be obtained in any case by the assignment of this sentence.

Look at the assignment, what do you see?
Yes, Window.pageyoffset (Safari) is placed in | | The middle position.

Because the system returns the last value by default when the number 0 is in the undefine or operation. In the operation of 0 = = Undefine;

When the page scroll bar is just at the top, that is, the scrolltop value is 0 o'clock, ie window.pageyoffset (Safari) returns to Undefine, when Window.pageyoffset (Safari) is placed on the last side of the operation, SC Rolltop return undefine, undefine use in the next operation will be an error.

Other browsers do not return undefine regardless of scrolltop assignment or order of operations. Safe to use.

So the end is still ie problem. Cup with ...

Spirit a little trance, do not know whether there is no clear expression.
But finally summed up this sentence experiment is OK, we rest assured use.

The

code is as follows:


var scrolltop = Document.documentElement.scrollTop | | Window.pageyoffset | | Document.body.scrollTop;

It's perfect. Gets the ScrollTop assignment statement.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.